Need to have a Required and Optional Fields in Django Formset

耗尽温柔 提交于 2019-12-18 09:39:50

问题


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

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

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 - 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

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)

回答1:


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)

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



来源:https://stackoverflow.com/questions/44159559/need-to-have-a-required-and-optional-fields-in-django-formset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!