我创建了一个最多可附加5张图像的formset;
1 - 但我希望验证仅在用户未附加任何图片(ValidationError('atleast 1 image is required'))
时运行,
2 - 此程序也不允许用户在附加1或2或3张图像时进行保存,这是我真正需要的。因此,如果有1张图像或2张图像,则应该允许保存。
3 - 我还需要默认选择1个单选按钮,以使所选图像成为模板中显示的图像
模板
<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)
答案 0 :(得分:0)
您始终可以将min_num
和max_num
传递给modelformset_factory
ImagesFormset = modelformset_factory(ProductImages,
fields=('media', 'featured_image'),
min_num=1,
max_num=5,
extra=5)
这将确保至少有1张图片,最多5张