Как я могу показать собственный список заказов?
Я хотел бы показать все заказы одного пользователя. Этот код работает отлично. Но проблема в том, что когда я делаю log out, то выдает следующую ошибку. Даже не переходит на предыдущую страницу. Что я могу сделать?
Ошибки:
AttributeError at /
'AnonymousUser' object has no attribute 'user_frontend_order'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.3
Exception Type: AttributeError
Exception Value:
'AnonymousUser' object has no attribute 'user_frontend_order'
Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py, line 247, in inner
Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.5
Python Path:
['D:\\1_WebDevelopment\\Business_Website',
'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages',
'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32',
'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib',
'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin',
'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Sun, 13 Mar 2022 18:12:22 +0000
Traceback Switch to copy-and-paste view
C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
D:\1_WebDevelopment\Business_Website\business_app\views.py, line 16, in index
queryset = request.user.user_frontend_order.all() …
просмотров:
def index(request):
total_user = User.objects.count()-1
frontend_order_list = request.user.user_frontend_order.all()
context = {
"total_user":total_user,
"frontend_order_list":frontend_order_list
}
return render(request,'0_index.html',context)
Модели:
class Frontend_Order(models.Model):
USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE,related_name='user_frontend_order')
Service_Type = models.CharField(max_length=250, null=True)
Price = models.CharField(max_length=250, null=True)
def __str__(self):
return str(self.pk)+ str(".") + str(self.USer)
Переходит на предыдущую страницу. Проблема в том, что при оценке логики работы index возникает проблема: он нацелен на поиск Frontend_Order объектов пользователя, но request.user является не User объектом, а AnonymousUser. Таким образом, вы должны сделать соответствующую проверку:
def index(request):
total_user = User.objects.count()-1
if request.user.is_authenticated:
frontend_order_list = request.user.user_frontend_order.all()
else:
frontend_order_list = Frontend_Order.objects.none()
context = {
'total_user': total_user,
'frontend_order_list': frontend_order_list
}
return render(request, '0_index.html', context)
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL[Django-doc] to refer to the user model, than to use theUsermodel [Django-doc] directly. For more information you can see the referencing theUsermodel section of the documentation.
Примечание: Модели в Django пишутся в PascalCase, а не snake_case, поэтому вы можете переименовать модель из
вFrontend_OrderFrontendOrder.