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