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

我正在尝试将动态选择列表绑定到ModelForm . 表单正确呈现 . 但是,当使用带有POST请求的表单时,我会返回一个空表单 . 我的目标是将该表单保存到数据库中(form.save()) . 任何帮助将非常感激 .

Model

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

from django.db import models
from multiselectfield import MultiSelectField

class VizInfoModel(models.Model):

     tog = MultiSelectField()
     vis = MultiSelectField()

Forms

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

View

实例化表单时从视图中传递选项 .

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})

Template

<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>

回答(1)

2 years ago

你're saying Django doesn' t进入你的 if request.method == 'POST' 区块 .

这告诉我们你're not sending your request through the POST method. Your template probably has an error in it, maybe you haven' t指定了 form 上的方法,或者你的按钮只是一个链接而不是提交?

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