需要在Django Formset中具有必需和可选字段 [英] Need to have a Required and Optional Fields in Django Formset

查看:174
本文介绍了需要在Django Formset中具有必需和可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个最多可以附加5张图片的表单;

I created a formset that has maximum of 5 images to be attached;

1 - ,但我希望验证仅在用户没有附加任何图像(ValidationError('atleast 1 image is required'))

1 - but I want the Validation to run only when the user has not attached any image(ValidationError('atleast 1 image is required')),

2 - 此程序也不允许用户保存1或2或3图像,我真正需要的。所以如果有1张图片或2张,那应该被允许保存。

2- This program is also not allowing the User to save when 1, or 2, or 3 images are attached, which I really need. So if there is 1 image or 2, that should be allowed to save.

3 - 我还需要制作1个单选按钮默认情况下选择,以使所选图像成为模板中显示的图像

3 - I also need to make the 1 radio-button to be selected by default, to make the selected image to be the one dispalyed in the template

模板

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

{% for hidden in form.hidden_fields %}
    {{ hidden }}
{% endfor %}

{{ form.as_p }}

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

{% for choice in formset %}
<div>
  <label>{{ choice.media }}</label>
  <input type="radio" name="featured">{{choice.featured_image.label }}
</div>
{% endfor %}
</div>

<input type="submit" value="{{ submit_btn }}">
</form>

forms.py

class ProductImagesForm(forms.ModelForm):
    media = forms.ImageField(label='Image', required=True)
    featured_image = forms.BooleanField(initial=True, required=True)
class Meta:
        model = ProductImages
        fields = ['media', 'featured_image']

ImagesFormset = modelformset_factory(ProductImages, fields=('media', 'featured_image'), extra=5)

views.py

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 or None)
        form_valid = form.is_valid()
        formset_valid = formset.is_valid()
        if (form.is_valid() and formset.is_valid()):
            seller = self.get_account()
            form.instance.seller = seller
            self.object = form.save()
            images_set = formset.save(commit=False)
            for img in images_set:
                img.product = self.object
                img.save()
            formset.save()
            return self.form_valid(form, formset)
        else:
            return self.form_invalid(form, formset)


推荐答案

始终将 min_num max_num 传递给modelformset_factory

You can always pass in min_num and max_num to the modelformset_factory

ImagesFormset = modelformset_factory(ProductImages, 
                                     fields=('media', 'featured_image'),  
                                     min_num=1,
                                     max_num=5,
                                     extra=5)

这将确保至少有一个图像和最多5个

This will ensure that there is at least 1 image and max 5

这篇关于需要在Django Formset中具有必需和可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆