Answer the question
In order to leave comments, you need to log in
I'm trying to place an order, but I constantly encounter errors of a different nature (now DoesNotExist at /make-order/), I don't understand what's wrong?
#models.py
User = get_user_model()
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='category', blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('products_by_category', args=[self.slug])
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='product', blank=True)
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_url(self):
return reverse('product_detail', args=[self.category.slug, self.slug])
def __str__(self):
return self.name
class Cart(models.Model):
cart_id = models.CharField(max_length=250, blank=True)
date_added = models.DateField(auto_now_add=True)
class Meta:
ordering = ['date_added']
db_table = 'Cart'
def __str__(self):
return self.cart_id
class CartItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
quantity = models.IntegerField()
active = models.BooleanField(default=True)
class Meta:
db_table = 'CartItem'
def sub_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product
class Customer(models.Model):
user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE)
phone = models.CharField(max_length=20, verbose_name='Номер телефона', null=True, blank=True)
address = models.CharField(max_length=255, verbose_name='Адрес', null=True, blank=True)
orders = models.ManyToManyField('Order', verbose_name='Заказы покупателя', related_name='related_order')
def __str__(self):
return "Покупатель: {} {}".format(self.user.first_name, self.user.last_name)
class Order(models.Model):
STATUS_NEW = 'new'
STATUS_IN_PROGRESS = 'in_progress'
STATUS_READY = 'is_ready'
STATUS_COMPLETED = 'completed'
BUYING_TYPE_SELF = 'self'
BUYING_TYPE_DELIVERY = 'delivery'
STATUS_CHOICES = (
(STATUS_NEW, 'Новый заказ'),
(STATUS_IN_PROGRESS, 'Заказ в обработке'),
(STATUS_READY, 'Заказ готов'),
(STATUS_COMPLETED, 'Заказ выполнен')
)
BUYING_TYPE_CHOICES = (
(BUYING_TYPE_SELF, 'Самовывоз'),
(BUYING_TYPE_DELIVERY, 'Доставка')
)
customer = models.ForeignKey(Customer, verbose_name='Покупатель', related_name='related_orders',
on_delete=models.CASCADE)
first_name = models.CharField(max_length=255, verbose_name='Имя')
last_name = models.CharField(max_length=255, verbose_name='Фамилия')
phone = models.CharField(max_length=20, verbose_name='Телефон')
cart = models.ForeignKey(Cart, verbose_name='Корзина', on_delete=models.CASCADE, null=True, blank=True)
address = models.CharField(max_length=1024, verbose_name='Адрес', null=True, blank=True)
status = models.CharField(
max_length=100,
verbose_name='Статус заказ',
choices=STATUS_CHOICES,
default=STATUS_NEW
)
buying_type = models.CharField(
max_length=100,
verbose_name='Тип заказа',
choices=BUYING_TYPE_CHOICES,
default=BUYING_TYPE_SELF
)
comment = models.TextField(verbose_name='Комментарий к заказу', null=True, blank=True)
created_at = models.DateTimeField(auto_now=True, verbose_name='Дата создания заказа')
order_date = models.DateField(verbose_name='Дата получения заказа', default=timezone.now)
def __str__(self):
return str(self.id)
#view.py
def home(request, category_slug=None):
category_page = None
products = None
if category_slug != None:
category_page = get_object_or_404(Category, slug=category_slug)
products = Product.objects.filter(category=category_page, available=True)
else:
products = Product.objects.all().filter(available=True)
return render(request, 'home.html', {'category': category_page, 'products': products})
def product(request, category_slug, product_slug):
try:
product = Product.objects.get(category__slug=category_slug, slug=product_slug)
except Exception as e:
raise e
return render(request, 'product.html', {'product': product})
def _cart_id(request):
cart = request.session.session_key
if not cart:
cart = request.session.create()
return cart
def add_cart(request, product_id):
product = Product.objects.get(id=product_id)
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
except Cart.DoesNotExist:
cart = Cart.objects.create(cart_id=_cart_id(request))
cart.save()
try:
cart_item = CartItem.objects.get(product=product, cart=cart)
if cart_item.quantity < cart_item.product.stock:
cart_item.quantity += 1
cart_item.save()
except CartItem.DoesNotExist:
cart_item = CartItem.objects.create(product=product, quantity=1, cart=cart)
cart_item.save()
return redirect('cart_detail')
def cart_detail(request, total=0, counter=0, cart_items=None):
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=cart, active=True)
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
counter += cart_item.quantity
except ObjectDoesNotExist:
pass
return render(request, 'cart.html', dict(cart_items=cart_items, total=total, counter=counter))
def cart_remove(request, product_id):
cart = Cart.objects.get(cart_id=_cart_id(request))
product = get_object_or_404(Product, id=product_id)
cart_item = CartItem.objects.get(product=product, cart=cart)
if cart_item.quantity > 1:
cart_item.quantity -= 1
cart_item.save()
else:
cart_item.delete()
return redirect('cart_detail')
def cart_remove_product(request, product_id):
cart = Cart.objects.get(cart_id=_cart_id(request))
product = get_object_or_404(Product, id=product_id)
cart_item = CartItem.objects.get(product=product, cart=cart)
cart_item.delete()
return redirect('cart_detail')
def signUpView(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
signup_user = User.objects.get(username=username)
user_group = Group.objects.get(name='User')
user_group.user_set.add(signup_user)
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
def loginView(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
return redirect('signup')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
def signoutView(request):
logout(request)
return redirect('login')
class MakeOrderView(View):
@transaction.atomic
def post(self, request, *args, **kwargs):
form = OrderForm(request.POST or None)
customer = Customer.objects.get(user=request.user)
print(customer)
if form.is_valid():
new_order = form.save(commit=False)
new_order.customer = customer
new_order.first_name = form.cleaned_data['first_name']
new_order.last_name = form.cleaned_data['last_name']
new_order.phone = form.cleaned_data['phone']
new_order.address = form.cleaned_data['address']
new_order.buying_type = form.cleaned_data['buying_type']
new_order.order_date = form.cleaned_data['order_date']
new_order.comment = form.cleaned_data['comment']
new_order.save()
new_order.cart = cart_detail
new_order.save()
customer.orders.add(new_order)
messages.add_message(request, messages.INFO, 'Спасибо за заказ! Менеджер с Вами свяжется')
return HttpResponseRedirect('/')
return HttpResponseRedirect('/checkout/')
class CheckoutView(View):
def get(self, request, *args, **kwargs):
categories = Category.objects.all()
form = OrderForm(request.POST or None)
context = {
'cart': cart_detail,
'categories': categories,
'form': form
}
return render(request, 'checkout.html', context)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question