Запрос, соответствующий продукту, не существует
я создаю небольшой вебмагазин, на странице товара я разместил форму заказа используя FormMixin и TemplateView, когда я отправляю заказ я получаю ошибку Page Not Found "No Order matches the given query."
Ниже вы можете проверить код
Models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255, unique=True, )
description = models.TextField(max_length=1500)
class Meta:
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
nominal_price = models.PositiveIntegerField(verbose_name='prix normal',)
reduced_price = models.PositiveIntegerField(blank=True, null=True)
quantity = models.PositiveIntegerField(default=10)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png")
def __str__(self):
return self.name
class Customer(models.Model):
full_name = models.CharField(max_length=150)
address = models.CharField(max_length=1500, null=True)
phone = models.IntegerField()
city = models.CharField(max_length=100)
email = models.EmailField(null=True)
class Order (models.Model):
product = models.ManyToManyField(Product, through='OrderProduct')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
Views.py
class ProductDetailView(FormMixin, TemplateView):
model = Product
template_name = 'product.html'
form_class = OrderForm
def get_success_url(self):
return reverse('index')
def post(self, request, *args, **kwargs):
context = self.get_context_data()
form = OrderForm(request.POST)
if context['form'].is_valid():
product = get_object_or_404(Order, product__name=self.kwargs['product_name'])
customer = form.save(commit=False)
Order.objects.create(product=product, customer=customer)
form.save()
return super(TemplateView, self)
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
context['product'] = Product.objects.get(name=self.kwargs['product_name'])
context['form'] = self.get_form()
return context
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Customer
fields = ['full_name', 'address', 'phone', 'city']
urls.py
path('', views.ProductListView.as_view(), name='index'),
Я что-то пропустил
Для работы с отношениями "многие ко многим" вы не можете напрямую установить product
из Order
. Также необходимо сначала создать order
, прежде чем вы сможете установить или добавить продукт:
order = Order.objects.create(customer=customer)
order.product.add(product)