在Django中将函数基视图转换为类基视图



如何将这些视图转换为类基视图,这个视图用于添加订单新订单,我想
将这个视图更改为类基视图,但我不能

def add_user_order(请求):

new_order_form = UserNewOrderForm(request.POST or None)

if new_order_form.is_valid():
order = Order.objects.filter(owner_id=request.user.id, is_paid=False).first()
if order is None:
order = Order.objects.create(owner_id=request.user.id, is_paid=False)
product_id = new_order_form.cleaned_data.get('product_id')
count = new_order_form.cleaned_data.get('count')
if count < 0:
count = 1
product = Product.objects.get_by_id(product_id=product_id)
order.orderdetail_set.create(product_id=product.id, price=product.price, count=count)
# todo: redirect user to user panel
return redirect(f'products/{product_id}/{product.title.replace(" ", "-")}')
return redirect('/')

您可以使用FormView[Django-doc]里面的form_valid函数会做大部分的逻辑:

class UserAddOrderView(FormView):
form_class = UserNewOrderForm
def form_valid(self, form):
order, __ = Order.objects.get_or_create(owner_id=request.user.id, is_paid=False)
self.product_id = product_id = new_order_form.cleaned_data.get('product_id')
count = new_order_form.cleaned_data.get('count')
if count < 0:
count = 1
order.orderdetail_set.create(product_id=product_id, price=product.price, count=count)
return super().form_valid(form)
def get_success_url(self):
return f'products/{product_id}/{product.title.replace(" ", "-")}'

然而,手工构造url不是好主意。您可以使用reverse(…)函数[Django-doc]。和鼻涕虫一样,不要用自己构造鼻涕虫,而是用slugify(…)[Django-doc]。通常,您还应该将段塞保存到它所属的模型中,以使(快速)查找成为可能。

相关内容

  • 没有找到相关文章

最新更新