0

我如何将 django formset 中的选择限制为最大 5 个。我的观点是:

file_attachment_formset = get_audioattachment_formset(FileAttachmentForm, extra=1, can_delete=True)

我的表格为:

class FileAttachmentForm(forms.ModelForm):
    class Meta:
        model = FileAttachment

    def __init__(self, *args, **kw):
        super(forms.ModelForm, self).__init__(*args, **kw)
        self.fields['audio_video'].widget.attrs['class'] = 'form-text'

def get_audioattachment_formset(form, formset = models.BaseInlineFormSet, **kwargs):
    return models.inlineformset_factory(Post, FileAttachment, form, formset, **kwargs)

模型.py:

class FileAttachment(models.Model):
    post          = models.ForeignKey(Post, related_name = 'file_attachments')
    picture       = models.ImageField(upload_to = 'uploads/picture/', null = True, blank = True)
    audio_video   = models.URLField(null = True, blank = True, verbose_name = "Audio/Video URL", verify_exists = True)

视图.py:

file_attachment_formset = get_audioattachment_formset(FileAttachmentForm, extra=1, can_delete=True, max_num=3)
if request.method == 'POST':
   postForm = MyPostForm(request.POST, instance = post)
   formset = file_attachment_formset(request.POST, request.FILES, instance = post)
   if formset.is_valid():
                #FileAttachment.objects.filter(post = newpost).delete()
                formset = file_attachment_formset(request.POST, request.FILES, instance = newpost)
                formset.save()
   else:
       formset = file_attachment_formset(instance = post)  

帮助我如何将图片的选择限制为最多 5 个?

4

1 回答 1

0

通过max_numformset 函数,

file_attachment_formset = get_audioattachment_formset(FileAttachmentForm, extra=1, can_delete=True, max_num=5)

这是我的猜测,通常max_num表单集作为一个 kwarg。试试看!

于 2012-09-17T07:38:09.940 回答