KeyError at / partners / create /' name'

时间:2017-10-12 14:55:07

标签: django django-forms django-views

我有一个与一对多关系产品相关的模型合作伙伴。我正在使用产品的inlineformsets,我发现以下错误,我不明白:" KeyError at / partners / create /' name'"

我的观点如下:

def partner_create(request):   
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404

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

    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:
                name = form["name"]
                description = form["description"]
                price = form["price"]
                image = form["image"]


                product = Product(partner=instance, name=name, description=description, price=price, product_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})

my forms.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",
            "name",
            "description",
            "price",
            "image",
        ]

我的models.py如下:

def upload_location(instance, filename):
    #filebase, extension = filename.split(".")
    # return "%s/%s" %(instance.name, instance.id)
    PartnerModel = instance.__class__
    exists = PartnerModel.objects.exists()
    if exists:
        new_id = PartnerModel.objects.order_by("id").last().id + 1
    else:
        new_id = 1
    file_name, file_extension = filename.split('.')
    return "%s/%s/%s-%s.%s" %('partner',instance.name, file_name, new_id, file_extension)


class Partner(models.Model):
    name = models.CharField(max_length=120)
    logo = models.ImageField(upload_to=upload_location, 
        null=True, 
        blank=True, 
        width_field="width_field", 
        height_field="height_field")
    banner_image = models.ImageField(upload_to=upload_location,
        null=True, 
        blank=True, 
        width_field="width_field", 
        height_field="height_field")
    mission = models.TextField()
    vision = models.TextField()
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    # text = models.TextField()
    website_link = models.CharField(max_length=120)
    fb_link = models.CharField(max_length=120)
    twitter_link = models.CharField(max_length=120)
    ig_link = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)


    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("partners:detail", kwargs={"slug": self.slug})
        # return "/partner/%s/" %(self.id)

    def get_markdown(self):
        mission = self.mission
        markdown_text = markdown(mission)
        return mark_safe(markdown_text)


#Creating a many to one relationship so that one can upload many Products
class Product(models.Model):
    partner = models.ForeignKey(Partner, default=None)
    name = models.CharField(max_length=120)
    product_image = models.ImageField(upload_to=upload_location,
    # product_image = models.ImageField(upload_to= (upload_location + '/' + name), Something like this need to append actual product name so these dont just get dumped in the media for partners
        null=True, 
        blank=True, 
        width_field="width_field", 
        height_field="height_field",
        verbose_name='Image',)
    description = models.TextField()
    price = models.DecimalField(max_digits=6, decimal_places=2, null=True)
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

    def __unicode__(self):              # __unicode__ on Python 2
        return self.name

我真的很想了解发生了什么,以及如何解决它或提示正确的方向。提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

要找出导致错误的原因,您应该在代码中添加一些打印或记录。 formset.cleaned_data的价值是多少?这是你认为它应该是什么?

有一种更简单的方法可以循环遍历formset的cleaned_data。文档展示了如何save a formset。您可以使用commit=False保存,然后在保存到数据库之前设置partner字段。

products = formset.save(commit=False)
for product in products:
    product.partner=instance
    product.save()

请注意,如果您这样做,则应该切换为modelformset_factory而不是inlineformset_factory,并从partner的字段列表中删除ProductForm

答案 1 :(得分:0)

formset表单保存方法似乎不正确,请使用类似

的内容
for form in formset.cleaned_data:
    if form.is_valid():
        name = form.cleaned_data.get("name")
        description = form.cleaned_data.get("description")
        price = form.cleaned_data.get("price")
        image = form.cleaned_data.get("image")

请知道这是否有效:)