2017-05-24 63 views
0

我創建了一個最多可以附加5個圖像的表單集;需要在Django Formset中有必需和可選的字段

1 -但我想僅當用戶沒有附加任何圖像(ValidationError('atleast 1 image is required'))的驗證運行,

2-此程序還沒有允許用戶時節省1或2,或者附上3張圖片,這是我真正需要的。所以如果有1張圖片或2張,應該允許保存。

3 -我還需要使1單選按鈕來默認選擇,以使所選擇的圖像被一個在模板dispalyed

模板

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

形式的.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

可以在min_nummax_num始終傳遞給modelformset_factory

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

這將確保至少有1圖像和最多5

+0

我已經這樣做了,但它仍然保存時,有沒有附加圖片 – dungu

+0

您是否正在驗證視圖中的formset? –

+0

是的,你可以看看我在上面提供的views.py中的驗證 – dungu

相關問題