可以使用 Django 表单进行可变数量的输入吗? [英] Variable number of inputs with Django forms possible?

查看:26
本文介绍了可以使用 Django 表单进行可变数量的输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 django 表单拥有可变数量的字段?

Is it possible to have a variable number of fields using django forms?

具体应用是这样的:

用户可以在图片上传表单中上传任意数量的图片.图片上传后,它们会被带到一个页面,在那里他们可以为图片命名和描述.图片的数量取决于用户选择上传的数量.

A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload.

那么如何让 django 使用可变数量的输入字段生成表单(如有必要,可以将其作为参数传递)?

So how do I get django to generate a form using a variable number of input fields (which could be passed as an argument if necessary)?

编辑:自 jeff bauer 的回答中提到的文章 已经写好了.

即这行代码似乎不起作用:

Namely this line of code which doesn't seem to work:

# BAD CODE DO NOT USE!!!
return type('ContactForm', [forms.BaseForm], { 'base_fields': fields })

这就是我想出的……


from tagging.forms import TagField
from django import forms

def make_tagPhotos_form(photoIdList):
    "Expects a LIST of photo objects (ie. photo_sharing.models.photo)"

    fields = {}

    for id in photoIdList:
        id = str(id)

        fields[id+'_name'] = forms.CharField()
        fields[id+'_tags'] = TagField()
        fields[id+'_description'] = forms.CharField(widget=forms.Textarea)

    return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields })

note tagging 不是 django 的一部分,但它是免费的并且非常有用.检查一下:django-tagging

note tagging is not part of django, but it is free and very useful. check it out: django-tagging

推荐答案

是的,可以在 Django 中动态创建表单.您甚至可以将动态字段与普通字段混合搭配.

Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.

class EligibilityForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(EligibilityForm, self).__init__(*args, **kwargs)
        # dynamic fields here ...
        self.fields['plan_id'] = CharField()
    # normal fields here ...
    date_requested = DateField()

要更好地阐述这项技术,请参阅 James Bennett 的文章:所以您想要动态表单?

For a better elaboration of this technique, see James Bennett's article: So you want a dynamic form?

http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/

这篇关于可以使用 Django 表单进行可变数量的输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆