本文介绍了可以使用Django形式进行可变数量的输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 使用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)? 编辑:自文章。这行代码似乎不起作用:Namely this line of code which doesn't seem to work:# BAD CODE DO NOT USE!!!return type('ContactForm', [forms.BaseForm], { 'base_fields': fields })这就是我想出的...So here is what I came up with...from tagging.forms import TagFieldfrom django import formsdef 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 })注释标记不是django的一部分,但它是免费的并且非常有用。检查一下: django-taggingnote 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形式进行可变数量的输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-29 17:30