【问题标题】:django, how to deal with modelForm with foreignkey?django,如何处理带有外键的modelForm?
【发布时间】:2020-05-21 09:38:27
【问题描述】:

我想用 modelForm 处理 foreignKey 并引发此错误:

ValueError at /3/
  The view main.views.ProductDetailView didn't return an
  HttpResponse object. It returned None instead.

问题出在 Wilaya 和 commune 领域,因为当我删除它们时一切正常。

在views.py中

class ProductDetailView(ModelFormMixin, DetailView):
    model = Produit
    context_object_name = 'produit'
    form_class = CheckoutCreateForm

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["form"] = self.get_form()
        context["wilayas"]= Wilaya.objects.all()
        context["communes"]= Commune.objects.all()
        return context

    def post(self, request, *args, **kwargs):
        # self.object = self.get_object()
        # form = self.get_form()
        form = CheckoutCreateForm(request.POST)
        if form.is_valid():
            checkout = form.save(commit=False)
            checkout.produit = self.get_object()
            checkout.prix = self.get_object().price
            checkout.save()
            wilaya = form.cleaned_data['wilaya']
            commune = form.cleaned_data['commune']
            quantity = form.cleaned_data['quantity']
            nom_du_client = form.cleaned_data['nom_du_client']
            prenom_du_client = form.cleaned_data['prenom_du_client']
            adresse_du_client = form.cleaned_data['adresse_du_client']
            print('jusque la cv')
            try:
                form = CheckoutCreateForm()
                return redirect(f'/{self.get_object().pk}')
            except:
                return redirect('/')

在models.py中

class Wilaya(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Commune(models.Model):
    Wilaya = models.ForeignKey(Wilaya, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Checkout(models.Model):
    produit = models.ForeignKey('Produit', on_delete=models.CASCADE)
    prix = models.IntegerField(default=0)
    nom_du_client = models.CharField(max_length=40)
    prenom_du_client = models.CharField(max_length=40)
    adresse_du_client = models.CharField(max_length=40)
    date_added = models.DateTimeField(auto_now_add=True)
    wilaya = models.ForeignKey(Wilaya, on_delete=models.SET_NULL, null=True, blank=True)
    commune = models.ForeignKey(Commune, on_delete=models.SET_NULL, null=True, blank=True)
    quantity = models.PositiveIntegerField(default=1)
    confirmer = models.BooleanField(default=False)

    def __str__(self):
        return str(self.produit)

在forms.py中

from django import forms 
from .models import Checkout, Commune , Wilaya
class CheckoutCreateForm(forms.ModelForm):
    class Meta:
        model = Checkout 
        fields = ['nom_du_client', 'prenom_du_client','adresse_du_client', 'quantity', 'wilaya', 'commune']

在 html 文件中:

  <form class="card-body" method='POST' id="checkoutForm" >
                  {% csrf_token %}
                  <!--Grid row-->
                  <div class="row">

                    <!--Grid column-->
                    <div class="col-md-6 mb-2">

                      <!--firstName-->
                      <div class="md-form ">
                        <input type="text" name="nom_du_client" id="firstName" class="form-control">
                        <label for="nom_du_client" class="">First name</label>
                      </div>
  .... rest of the form 

    <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>

                </form>

【问题讨论】:

    标签: python django django-models django-forms modelform


    【解决方案1】:

    这个错误是不言自明的:

    视图main.views.ProductDetailView 没有返回HttpResponse 对象。它返回了None

    如果您查看代码的简化版本:

    class ProductDetailView(ModelFormMixin, DetailView):
        def post(self, request, *args, **kwargs):
            ...
    
            if form.is_valid():
                ...
                try:
                    ...
                    return redirect(f'/{self.get_object().pk}')
                except:
                    return redirect('/')
    

    您会注意到,如果表单无效,post() 方法会返回 None

    一种可能的解决方案是在末尾也有一个return redirect(...)

    class ProductDetailView(ModelFormMixin, DetailView):
        def post(self, request, *args, **kwargs):
            ...
    
            if form.is_valid():
                ...
                try:
                    ...
                    return redirect(f'/{self.get_object().pk}')
                except:
                    pass
    
            return redirect('/')
    

    【讨论】:

    • 确实错误消失了,但它在实例模型中引发了另一个问题,我在数据库中什么也没有得到,而不是新的结帐我该如何解决这个问题?再次感谢您
    猜你喜欢
    • 1970-01-01
    • 2013-05-03
    • 2013-09-05
    • 1970-01-01
    • 2015-09-24
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多