пожалуйста, я пытался исправить это, но я не смог решить это. Я получаю эту страницу ошибки всякий раз, когда пытаюсь загрузить url locahost заказа: 8000 / orders /
DoesNotExist at /orders/
UserCheckout matching query does not exist.
Request Method: GET
Request URL: http://localhost:8000/orders/
Django Version: 1.8.4
Exception Type: DoesNotExist
Exception Value: UserCheckout matching query does not exist.
Exception Location: /home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/query.py in get, line 334
Python Executable: /usr/local/bin/uwsgi
Python Version: 3.6.0
Python Path:
['/home/rayup/hotels',
'/var/www',
'.',
'',
'/var/www',
'/home/rayup/.virtualenvs/secondenv/lib/python36.zip',
'/home/rayup/.virtualenvs/secondenv/lib/python3.6',
'/home/rayup/.virtualenvs/secondenv/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages']
Server time: Tue, 13 Nov 2018 18:39:47 +0000
ПОЖАЛУЙСТА, ЗДЕСЬ ОБРАТНАЯ СВЯЗЬ :::
Environment:
Request Method: GET
Request URL: http://www.rayconsult.com.ng/orders/
Django Version: 1.8.4
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'shop',
'orders',
'crispy_forms',
'django_filters',
'registration',
'bootstrap3',
'cart',
'contact',
'newsletter',
'newsletter1',
'django.contrib.sites']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/rayup/hotels/orders/mixins.py" in dispatch
11. return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/list.py" in get
159. self.object_list = self.get_queryset()
File "/home/rayup/hotels/orders/views.py" in get_queryset
40. user_checkout = UserCheckout.objects.get(id=user_check_id)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
127. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/query.py" in get
334. self.model._meta.object_name
Exception Type: DoesNotExist at /orders/
Exception Value: UserCheckout matching query does not exist.
Эта строка кода в моем views.py вызывает проблему ::
user_checkout = UserCheckout.objects.get(id=user_check_id)
У меня есть представление на основе классов под названием OrderList в моем views.py .
По сути, я хочу, чтобы список (список заказов), возвращаемый в шаблоне, был специфичен для каждого пользователя при входе в систему
Вот мои views.py
from django.contrib import messages
from django.http import Http404
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView, FormView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from .forms import AddressForm, UserAddressForm
from .mixins import CartOrderMixin, LoginRequiredMixin
from .models import UserAddress, UserCheckout, Order
class OrderList(LoginRequiredMixin, ListView):
queryset = Order.objects.all()
def get_queryset(self):
user_check_id = self.request.user.id
user_checkout = UserCheckout.objects.get(id=user_check_id)
return super(OrderList, self).get_queryset().filter(user=user_checkout)
class OrderDetail(DetailView):
model = Order
def dispatch(self, request, *args, **kwargs):
try:
user_check_id = self.request.session.get("user_checkout_id")
user_checkout = UserCheckout.objects.get(id=user_check_id)
except UserCheckout.DoesNotExist:
user_checkout = UserCheckout.objects.get(user=request.user)
except:
user_checkout = None
obj = self.get_object()
if obj.user == user_checkout and user_checkout is not None:
return super(OrderDetail, self).dispatch(request, *args, **kwargs)
else:
raise Http404
Вот models.py
from decimal import Decimal
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import pre_save, post_save
from cart.models import Cart
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) #not required
email = models.EmailField(unique=True)
braintree_id = models.CharField(max_length=120, null=True, blank=True)
def __str__(self): #def __str__(self):
return self.email
@property
def get_braintree_id(self,):
instance = self
if not instance.braintree_id:
result = braintree.Customer.create({
"email": instance.email,
})
if result.is_success:
instance.braintree_id = result.customer.id
instance.save()
return instance.braintree_id
def get_client_token(self):
customer_id = self.get_braintree_id
if customer_id:
client_token = braintree.ClientToken.generate({
"customer_id": customer_id
})
return client_token
return None
class Order(models.Model):
status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created')
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
user = models.ForeignKey(UserCheckout, null=True)
billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True)
shipping_address = models.ForeignKey(UserAddress, related_name='shipping_address', null=True)
shipping_total_price = models.DecimalField(max_digits=50, decimal_places=2, default=5.99)
order_total = models.DecimalField(max_digits=50, decimal_places=2, null=True )
order_id = models.CharField(max_length=20, null=True, blank=True)
def __str__(self):
return str(self.cart.id)
class Meta:
ordering = ['-id']
def get_absolute_url(self):
return reverse("order_detail", kwargs={"pk": self.pk})
def mark_completed(self, order_id=None):
self.status = "paid"
if order_id and not self.order_id:
self.order_id = order_id
self.save()
Вот шаблон order_list.html
{% if object_list|length <= 0 %}
<div class='col-sm-6 col-sm-offset-3 text-center'>
<p class='lead'>
You do not currently have orders.
</p>
</div>
{% else %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>Your Orders</h1>
<table class='table'>
{% for object in object_list %}
<tr>
<td>
<a href='{{ object.get_absolute_url }}'>View #{% if object.order_id %}{{ object.order_id }}{% else %}{{ object.id }}{% endif %}</a>
</td>
<td>
Item Count: {{ object.cart.items.count }}
</td>
</tr>
{% endfor %}
</table>
</div>
{% endif %}
Вот основной URL (т. Е. URL проекта ) urls.py для страницы заказа
urlpatterns = [
url(r'^orders/$', OrderList.as_view(), name='orders'),
url(r'^orders/(?P<pk>\d+)/$', OrderDetail.as_view(), name='order_detail'),
]
Пожалуйста, я хочу дать вам, ребята, любую дополнительную информацию, которая вам нужна.
Проблема в функции def get_queryset (self): . Мне нужно иметь возможность настроить его так, чтобы он возвращал только список заказов на основе текущего пользователя, вошедшего в систему.
Однако я мог получить доступ к каждому отдельному заказу (то есть подробный обзор, набрав URL, известный от администратора.)
введите описание изображения здесь
Спасибо и надеюсь здесь от вас всех