我在尝试保存此表单时收到以下错误

时间:2017-10-09 19:47:58

标签: django django-models django-forms django-views

以下是错误:我们非常感谢任何有关正在发生的事情以及如何解决问题的帮助

Cannot assign '<PartnerForm bound=True, valid=True, fields=(name;logo;banner_image;mission;vision;website_link;fb_link;twitter_link;ig_link)>': "Product.partner" must be a "Partner" instance.

我试图在两个模型之间添加一对多的关系。 'one'模式是'合作伙伴'。 'many'是'Product',包含图片描述,价格等。

以下是我的views.py

def partner_create(request):

#Trying to add multiple product functionality
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404

    ProductFormSet = inlineformset_factory(Partner, Product, form=ProductForm, extra=3)

    if request.method == 'POST':
        partnerForm = PartnerForm(request.POST or None, request.FILES or None)
        formset = ProductFormSet(request.POST, request.FILES, queryset=Product.objects.none())

        if partnerForm.is_valid() and formset.is_valid():

            instance = partnerForm.save(commit=False)
            instance.save()


            for form in formset.cleaned_data:
                image = form['image']
                product = Product(partner=partnerForm, image=image)
                product.save()
            messages.success(request, "Partner Successfully Created")
        else:
            print partnerForm.errors, formset.errors
    else:
        partnerForm = PartnerForm()
        formset = ProductFormSet(queryset=Product.objects.none())
    return render(request, "partner_form.html", {"partnerForm": partnerForm, "formset": formset})

这是我的admin.py

class ProductImageInline(admin.TabularInline):
    model = Product
    extra = 3

#This works originally but doesn't do multiple products
class PartnerModelAdmin(admin.ModelAdmin):
    list_display = ["__unicode__", "timestamp"]
    inlines = [ProductImageInline,]
    class Meta:
        model = Partner

admin.site.register(Partner, PartnerModelAdmin)

这是我的form.py

class PartnerForm(forms.ModelForm):
    mission = forms.CharField(widget=PagedownWidget(show_preview=False))
    vision = forms.CharField(widget=PagedownWidget(show_preview=False))
    # publish = forms.DateField(widget=forms.SelectDateWidget)
    class Meta:
        model = Partner
        fields = [
            "name",
            "logo",
            "banner_image",
            "mission",
            "vision",
            "website_link",
            "fb_link",
            "twitter_link",
            "ig_link",
        ]

class ProductForm(forms.ModelForm):
    image = forms.ImageField(label='Image')
    class Meta:
        model = Product
        fields = [
            "partner",
            "image",
            "description",
            "price"
        ]

1 个答案:

答案 0 :(得分:3)

错误非常明显。在行

product = Product(partner=partnerForm, image=image)
product.save()

您正在为您的产品分配PartnerForm,同时期望合作伙伴实例!将其更改为

product = Product(partner=instance, image=image)
product.save()

(实例是我上面看到的合作伙伴实例),它会起作用。