【问题标题】:Limiting formset choice using django使用 django 限制表单集选择
【发布时间】:2012-09-17 07:19:41
【问题描述】:

如何将 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)

views.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 个?

【问题讨论】:

    标签: python django formset


    【解决方案1】:

    用formset函数传递max_num

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

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

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2011-11-26
      • 2011-06-11
      相关资源
      最近更新 更多