我的modelformset_factory没有保存图像(我使用了基于类的视图),但在使用管理员端

时间:2017-05-17 07:14:45

标签: python django django-forms django-templates django-views

我在创建新产品时遇到了不保存图像的挑战。表单渲染得很好,图像上传但从未保存,直到我使用管理员上传并保存它,这就是在我创建的产品上可见时。

我认为我在views.py中的班级ProductCreateView()中遗漏了一些内容,特别是在def post()中。 帮我解决一下。

models.py

def product_download(instance, filename):
  return '%s/%s' %(instance.product.slug, filename)

class ProductImages(models.Model):
    product = models.ForeignKey(Product)
    title = models.CharField(max_length=120)
    media = models.ImageField(upload_to=product_download, 
        width_field='max_width', 
        height_field='max_height',
        null=True, blank=True)
    max_width = models.CharField(max_length=100, null=True, blank=True)
    max_height = models.CharField(max_length=100, null=True, blank=True)
    featured_image = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return unicode(self.media)

views.py

表单正在保存其信息,但formset不保存图像

from .forms import ProductModelForm, ProductImagesForm, ImagesFormset

class ProductCreateView(CreateView):

    def form_invalid(self, form, formset):
        return self.render_to_response(self.get_context_data(form=form, formset=formset))

    def form_valid(self, form, formset):
        return HttpResponseRedirect(self.get_success_url())

    def get(self, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        formset = ImagesFormset(queryset=ProductImages.objects.none())
        return self.render_to_response(self.get_context_data(form=form, formset=formset))

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        formset = ImagesFormset(self.request.POST, self.request.FILES)
        form_valid = form.is_valid()
        formset_valid = formset.is_valid()
        if form_valid and formset_valid:
            user = self.request.user
            form.instance.user = user
            self.object = form.save()
            media = formset.save(commit=False)
            for img in media:
                if hasattr(self.model, 'product'):
                    img.save()
                    formset = self.object
            formset.save()  
            return self.form_valid(form, formset)
        else:
            return self.form_invalid(form, formset)

forms.py

class ProductImagesForm(forms.ModelForm):
    media = forms.ImageField(label='Image')
    featured_image = forms.BooleanField(initial=True) 

    def __init__ (self, *args, **kwargs):
        super(ProductImages, self).__init__(*args, **kwargs)
        self.fields['featured_image'] = forms.BooleanField( widget = forms.RadioSelect(attrs={'checked': 'true'}, choices=((self.prefix, 'featured'),)))


    def add_prefix(self, field):
        if field == 'featured_image': return field
        else: return self.prefix and ('%s-%s' % (self.prefix, field)) or field

    class Meta:
        model = ProductImages
        fields = ['media', 'featured_image', ]
    ImagesFormset = modelformset_factory(ProductImages, fields=('media', 'featured_image'), extra=1, max_num=4)

模板

<form enctype="multipart/form-data" action="" method="POST"> {% csrf_token %} 

{{ form.as_p }}

{{ formset.management_form }}
<div class="link-formset">

{{  formset .as_p }}

</div>
</form>

3 个答案:

答案 0 :(得分:1)

如果这个答案有误,请原谅我的错误。

我认为错误就在这里,

<?php

class MyClass {

    function __constructor() {
        $temp["var_1"] = $_POST['var_1'];
        $temp["var_2"] = $_POST['var_2'];
    }

    function firstMethod() {
        echo 'output var 1 from contructor';
        echo $this->temp["var_1"];
    }

    function secMethod() {
        echo 'output var 2 from contructor';
        echo 'test2';
        echo $this->temp["var_2"];
    }

}

答案 1 :(得分:1)

经过长时间的阅读后,我终于找到了丢失的部分,将图像与产品相关联,现在保存并生成图像

if form_valid and formset_valid:
            seller = self.get_account()
            form.instance.seller = seller
            self.object = form.save()
            media = formset.save(commit=False)
            for img in media:
                img.product = self.object
                img.save()
            formset.save()

答案 2 :(得分:1)

这种方式更简单,只需将其与产品相关联即可解决问题

if form_valid and formset_valid:
            seller = self.get_account()
            form.instance.seller = seller
            self.object = form.save()
            media = formset.save(commit=False)
            for img in media:
                img.product = self.object
                img.save()
            formset.save()