2017-06-18 97 views
0

当我提交这个表格&所有字段都被正确填充时,form.is_valid()返回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()) 

回答

1

你在表单中传递的数据,在这里:

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

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

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

取出custom_choices=None

+0

事实上,这是问题!非常感谢:D我一直坚持一段时间!!! –

+0

干杯!你能标记答案已解决吗? :) – SebCorbin

2

你已经改变了形式的签名,以便第一位置参数是custom_choices。不要这样做。

您似乎实际上并未从您的视图中传递该值,因此您应该完全删除它。但是,如果你需要它,你应该从kwargs字典得到它:

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