将动态选择绑定到 Django 中的 ModelForm



我正在尝试将动态选项列表绑定到ModelForm。窗体已正确呈现。但是,当将表单与 POST 请求一起使用时,我返回了一个空表单。我的目标是将该表单保存到数据库中(form.save(((。任何帮助将不胜感激。

我正在使用多项选择字段 ( https://github.com/goinnn/django-multiselectfield (

from django.db import models
from multiselectfield import MultiSelectField
class VizInfoModel(models.Model):
     tog = MultiSelectField()
     vis = MultiSelectField()

形式

class VizInfoForm(forms.ModelForm):
    class Meta:
        model = VizInfoModel
        fields = '__all__'
    def __init__(self,choice,*args,**kwargs):
        super(VizInfoForm, self).__init__(*args,**kwargs)
        self.fields['tog'].choices = choice 
        self.fields['vis'].choices = choice

视图

实例化窗体时,将从视图传递选项。

def viz_details(request):
    options = []
    headers = request.session['headers']
    for header in headers :
        options.append((header, header))
    if request.method == 'POST':
        form = VizInfoForm(options, request.POST)
        #doesnt' get into the if statement since form is empty! 
        #choices are not bounded to the model although the form is perfectly rendered           
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/upload')
    else:
        #this works just fine
        form = VizInfoForm(options) 
        return render(request, 'uploads/details.html', {'form': form}) 

模板

  <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
         <p>Choose variables to toggle between</p>
        {{ form.tog }}
        <br></br>
        <p>Choose variable to be visualized</p>
        {{ form.vis }}
        <br></br>
        <button type="submit">Submit</button>
    </form>

你是说Django不会进入你的if request.method == 'POST'块。

这告诉我们您没有通过 POST 方法发送请求。您的模板可能有错误,也许您没有在form上指定方法,或者您使按钮只是一个链接而不是提交?

显示您的模板,以便我们可以说更多,除非这足以解决您的问题!

最新更新