form_valid在Django上不能与foregin_key一起使用

mgdq6dx1  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(121)

我想插入新的报价。但总是错误“无法分配“4030”:“Quotation.contact“必须是“Contact”示例。”我还想使用foreign_key,因此需要示例Contact。

class QuotationCreateView(CreateView):
    model = Quotation
    form_class = QuotationForm
    template_name = "quotation_form.html"

    def form_valid(self, form):
        contact_id = form.cleaned_data['contact']
        contact_instance = Contact.objects.get(pk=contact_id)
        self.object = form.save(commit=False)
        self.object.contact = contact_instance
        self.object.save()

        return super(QuotationCreateView, self).form_valid(form)

    def get_success_url(self):
        return reverse('quotation:list')

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        username = self.request.session.get('user')['name']
        kwargs['initial'] = {'our_charge_string': username}
        return kwargs
class Quotation(models.Model):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
    our_charge_string = models.CharField(max_length=30)
class Contact(models.Model):
    our_charge_string = models.CharField(max_length=30, null=True)
    reception_datetime = models.DateTimeField(editable=True)
class QuotationForm(forms.ModelForm):
    contact = forms.IntegerField(label='連絡ID')
    our_charge_string = forms.CharField(label='当社担当者', max_length=30)

    class Meta:
        model = Quotation
        fields = ("contact", "our_charge_string", "car_type_string", "loading_memo_string",
                  "loading_place_string", "delivery_memo_string", "delivery_place_string", "transit_place_string",
                  "item_string", "memo_string", "customer_id",)

我在form_valid行上放了一个断点。

ujv3wf0j

ujv3wf0j1#

错误消息“无法分配”4030:“Quotation.contact”必须是“联系人”示例。“告诉您正在尝试为Quotation模型中的联系人字段分配整数值。但是,contact字段是外键,这意味着它必须是Contact模型的示例。
要解决这个问题,您需要更改从表单获取contact_id值的方式。在form_valid()方法中,当前从cleaned_data字典获取contact_id值。但是,cleaned_data字典只包含用户输入到表单中的值。contact_id值不是由用户输入的,因此它不会出现在cleaned_data字典中。
相反,您需要从表单本身获取contact_id值。QuotationForm模型上的联系人字段是forms.IntegerField。这意味着用户在字段中输入的值将是一个整数。可以使用此整数值获取用户选择的Contact示例。
下面是你需要修改的代码:

def form_valid(self, form):
    contact_id = form.cleaned_data['contact']
    # This will raise an exception if the user did not select a contact.
    contact_instance = Contact.objects.get(pk=contact_id)
    self.object = form.save(commit=False)
    self.object.contact = contact_instance
    self.object.save() 
return super(QuotationCreateView, self).form_valid(form)

Once you have made this change, you should be able to create new Quotation objects without any errors.

相关问题