所有字段都给这个字段是必填错误

All fields give this field is required error

当我提交此表单并正确填充所有字段时,form.is _valid() returns false 并且所有字段都给出:此字段为必填错误,即使是 CharField!

有人能看出哪里出了问题吗? 这是我的表格:

class TemplateConfiguredForm(forms.Form):
    """This form represents the TemplateConfigured Form"""
    template = forms.ChoiceField(widget=forms.Select(attrs={'id':'TemplateChoice'}))
    logo = forms.ImageField( widget = forms.FileInput(attrs={'id': 'inputLogo'}))
    image = forms.ImageField(widget = forms.FileInput(attrs={'id': 'inputImage'}))
    message = forms.CharField(widget = forms.Textarea(attrs={'id': 'inputText', 'rows':5, 'cols':25}))

    def __init__(self, custom_choices=None, *args, **kwargs):
        super(TemplateConfiguredForm, self).__init__(*args, **kwargs)

        r = requests.get('http://127.0.0.1:8000/sendMails/api/templates/?format=json')
        json = r.json()

        custom_choices=( ( template['url'], template['name']) for template in json)

        if custom_choices:
            self.fields['template'].choices = custom_choices

这是我的模板:

<form id="template_form"  method="post" role="form"  enctype="multipart/form-data" action="{% url 'create_templates' %}" >
 {% csrf_token %}

{{ form.as_p }}

    {% buttons %}
    <input type="submit"  value="Save Template"/>
  {% endbuttons %}



</form>

这是我的观点:

def create_templates(request):

    if request.method == 'POST':

        form = TemplateConfiguredForm(request.POST, request.FILES)

        if form.is_valid():

            template_configured = TemplateConfigured()
            template_configured.owner = request.user
            template_configured.logo = form.cleaned_data["logo"]
            template_configured.image = form.cleaned_data["image"]
            template_configured.message = form.cleaned_data["message"]

            template = form.cleaned_data['template']

            template = dict(form.fields['template'].choices)[template]

            template_configured.template = Template.objects.get(name = template)

            template_configured.save()
            saved = True


        else:
            print form.errors


    else:
        form = TemplateConfiguredForm()


    return render(request, 'sendMails/createTemplates.html', locals())

您在表单中传递的数据,此处:

form = TemplateConfiguredForm(request.POST, request.FILES)

被您签名的第一个关键字参数捕获:

def __init__(self, custom_choices=None, *args, **kwargs):

删除 custom_choices=None

您已经更改了表单的签名,因此第一个位置参数是 custom_choices。不要那样做。

从您的角度来看,您似乎实际上根本没有传递该值,因此您可能应该将其完全删除。但是如果你确实需要它,你应该从 kwargs 字典中获取它:

def __init__(self, *args, **kwargs):
    custom_choices = kwargs.pop('custom_choices')
    super(TemplateConfiguredForm, self).__init__(*args, **kwargs)