2017-10-09 105 views
0

這裏的時候,下面的錯誤錯誤:任何幫助undestanding正在發生什麼,以及如何解決這將是非常讚賞我正在試圖挽救這種形式

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. 

我想添加一個以兩種模式之間的許多關係。 '一'模式是'合作伙伴'。在 '多' 是 '產品' 包含圖像說明,價格等

這裏是我的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" 
     ] 

回答

3

錯誤非常明顯。在行

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

您正在爲您的產品分配PartnerForm,而它期望一個合作伙伴實例!將其更改爲

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

(實例是我從上面看到的合作伙伴實例),它將起作用。

相關問題