我從事一個專案已經有一段時間了,我有一個名為 Item 的資源。
如果專案與用戶來自同一公司,則只能查看專案詳細資訊視圖。如果不是,它應該是 404。這是我擁有的代碼:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# To only show items in your company
if (context['item'].company != getCompany(self.request.user)):
return HttpResponseNotFound
return context
getCompany是我為檢查用戶公司而撰寫的函式。該公司處于定制Profile模式。這個功能有效,我已經多次使用它來做其他事情
現在我希望從另一家公司購買商品時會出現 404,但出現了以下錯誤:
Internal Server Error: /fr/items/5/
Traceback (most recent call last):
File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response
response = response.render()
File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/response.py", line 114, in render
self.content = self.rendered_content
File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/response.py", line 92, in rendered_content
return template.render(context, self._request)
File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/backends/django.py", line 58, in render
context = make_context(
File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/context.py", line 278, in make_context
raise TypeError(
TypeError: context must be a dict rather than type.
編輯:
我錯過了什么?
uj5u.com熱心網友回復:
該get_context_data(...)方法應該回傳一個dict物件。在您的情況下,您回傳的HttpResponseNotFound是不正確的。
引發錯誤的簡單方法404是使用Http404類引發例外
from django.http import Http404
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# To only show items in your company
if (context['item'].company != getCompany(self.request.user)):
raise Http404
return context
uj5u.com熱心網友回復:
作為Django 檔案
def get_context_data(self, **kwargs):
習慣于
回傳表示模板背景關系的字典。提供的關鍵字引數將構成回傳的背景關系
并且您正在嘗試回傳HttpResponseNotFound,這將不起作用,您應該回傳 dict 型別
uj5u.com熱心網友回復:
而是引發PermissionDenied錯誤,然后錯誤地回傳 aResponse作為背景關系,它提供了更好的含義,然后 Django 將回傳通常的 403 頁面。
from django.core.exceptions import PermissionDenied
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# To only show items in your company
if (context['item'].company != getCompany(self.request.user)):
raise PermissionDenied("You are not authorized to view the requested company")
return context
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/518637.html
上一篇:public、max-age和s-maxage之間的區別
下一篇:Python獲取請求:ssl.SSLCertVerificationError:[SSL:CERTIFICATE_VERIFY_FAILED]
