简体   繁体   English

不保存数据django外键模型

[英]Doesn't save data django Foreignkey model

I've two model.我有两个模型。 I would like to save data from ForeignKey model.我想保存来自 ForeignKey 模型的数据。 I'm created a modelform and save with my main foreignkey model.我创建了一个模型表单并与我的主要外键模型一起保存。 But I got this error ValueError at /c/customer/1/ Cannot assign "'1'": "BillingData.customer" must be a "CustomerData" instance.但我ValueError at /c/customer/1/ Cannot assign "'1'": "BillingData.customer" must be a "CustomerData" instance.收到此错误ValueError at /c/customer/1/ Cannot assign "'1'": "BillingData.customer" must be a "CustomerData" instance.

I created Django model form and hocked up with view.我创建了 Django 模型表单并使用了视图。

models.py file模型.py文件

class CustomerData(models.Model):
    customer_name = models.CharField(max_length=100)
    customer_no = models.CharField(max_length=100, default='', blank=True)
    mobile_number = models.IntegerField()
    alternative_phone = models.IntegerField(null=True, blank=True)
    union_name = models.ForeignKey(UnionName, on_delete=models.SET_NULL, null=True)
    word_name = models.ForeignKey(UnionWordName, on_delete=models.SET_NULL, null=True)
    full_address = models.CharField(max_length=200, null=True, blank=True)
    create_date = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return '%s, Mobile: %s' % (self.customer_name, self.mobile_number)

    def get_absolute_url(self):
        return reverse('customer_data', kwargs={'pk': self.pk})


class BillingData(models.Model):
    bill_no = models.CharField(max_length=100, default='', blank=True)

    customer = models.ForeignKey(CustomerData, on_delete=models.CASCADE)
    sales_person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    customer_money = models.IntegerField()
    create_date = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return '%s %s' % (self.customer.customer_name, self.create_date.date())

    def get_absolute_url(self):
        return reverse('customers.views.BillingPage', kwargs={'pk': self.pk})

forms.py file .py 文件

class BillCreateForms(forms.ModelForm):
    bill_no = forms.CharField(max_length=100)
    customer = forms.ChoiceField(choices=[(x.id, x.customer_name) for x in CustomerData.objects.all()])
    customer_money = forms.IntegerField()

    def save(self, commit=True):
        instance = super(BillCreateForms, self).save(commit=False)
        customer_pk = self.cleaned_data['customer']

        instance.customer = CustomerData.objects.get(pk=customer_pk)
        instance.save(commit)
        return instance

    class Meta:
        model = BillingData
        fields = ('bill_no', 'customer', 'customer_money',)

views.py file视图.py 文件

class CustomerDataView(FormMixin, generic.DetailView):
    model = CustomerData
    form_class = BillCreateForms
    template_name = "customers/customerdata_detail.html"
    print(form_class)

    success_url = '/c/'

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

I expect data save with foreignkey relation data.我希望使用外键关系数据保存数据。 But doesn't save here.但不保存在这里。

You can't fix this problem in the save method, because the error happens before it gets that far. 您无法在save方法中解决此问题,因为该错误会在此之前发生。

You should be using a ModelChoiceField, not a ChoiceField. 您应该使用ModelChoiceField,而不是ChoiceField。 Not only would this fix the problem, it would also let you remove your entire save method. 这不仅可以解决问题,还可以让您删除整个保存方法。

customer = forms.ModelChoiceField(queryset=CustomerData.objects.all())

Change this line 更改此行

instance.customer = CustomerData.objects.get(pk=customer_pk)

to

instance.customer_id = CustomerData.objects.get(pk=customer_pk).pk

Model:模型:

class Blog(models.Model):
    # ...
    pass

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE, null=True)

Set object设置对象

b = Blog.objects.get(id=1)
e = Entry.objects.get(id=234)
b.entry_set.add(e) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM