Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django表单未呈现_Django_Django Forms - Fatal编程技术网

Django表单未呈现

Django表单未呈现,django,django-forms,Django,Django Forms,我在forms.py中有以下表单: class ContractForm(forms.Form): title = forms.CharField() start_date = forms.DateField() end_date = forms.DateField() description = forms.CharField(widget=forms.Textarea) client = forms.ModelChoiceField(queryset=

我在forms.py中有以下表单:

class ContractForm(forms.Form):
    title = forms.CharField()
    start_date = forms.DateField()
    end_date = forms.DateField()
    description = forms.CharField(widget=forms.Textarea)
    client = forms.ModelChoiceField(queryset=Client.objects.all())

    def __init__(self, user, *args, **kwargs):
        super(ContractForm, self).__init__(*args, **kwargs)
        self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user=user))
        clients = Client.objects.filter(user = user)
        for client in clients:
            print client   
在我看来,该方法如下所示:

def addContract(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/contractManagement/login/?next=%s' % request.path)
else:   
    if request.method == 'POST':
        contractForm = ContractForm(request.POST)
        title = request.POST['title']
        start_date = request.POST['start_date']
        end_date = request.POST['end_date']
        description = request.POST['description']
        client = request.POST['client']
        user = request.user
        contract = Contract(title,start_date,end_date,description,client,user)
        contract.save()
        return HttpResponseRedirect('../../accounts/profile/')
    else:
        user = request.user
        print user.username
        contractForm = ContractForm(user)
        return render_to_response('newcontract.html', {'contractForm': contractForm})
<html>
<head>
</head>
<body>
{% if contractForm.errors %}
<p style="color: red;">
    Please correct the error{{ contractForm.errors|pluralize }} below.
</p>
{% endif %}
<form method="POST" action="">    
    <table>
        {{ contractForm.as_table }}
    </table> 
    <input type="submit" value="Submit" />
</form> 
 </body>
</html>
但是表单不会在浏览器中呈现。所有显示的是提交按钮。我的HTML如下所示:

def addContract(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/contractManagement/login/?next=%s' % request.path)
else:   
    if request.method == 'POST':
        contractForm = ContractForm(request.POST)
        title = request.POST['title']
        start_date = request.POST['start_date']
        end_date = request.POST['end_date']
        description = request.POST['description']
        client = request.POST['client']
        user = request.user
        contract = Contract(title,start_date,end_date,description,client,user)
        contract.save()
        return HttpResponseRedirect('../../accounts/profile/')
    else:
        user = request.user
        print user.username
        contractForm = ContractForm(user)
        return render_to_response('newcontract.html', {'contractForm': contractForm})
<html>
<head>
</head>
<body>
{% if contractForm.errors %}
<p style="color: red;">
    Please correct the error{{ contractForm.errors|pluralize }} below.
</p>
{% endif %}
<form method="POST" action="">    
    <table>
        {{ contractForm.as_table }}
    </table> 
    <input type="submit" value="Submit" />
</form> 
 </body>
</html>

forms.ModelChoiceField
queryset
参数应为queryset。应改为:

self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user=user))
您必须先在表单中声明它,然后再在
\uuuu init\uuu()方法中重写它:

class ContractForm(forms.Form):
    ...
    client = forms.ModelChoiceField(queryset=Client.objects.all())

除了Arnaud指出的QuerySet问题之外,这里还有很多错误

首先,当您实例化表单以响应GET时,您需要执行
contractForm=contractForm(用户)
。但是表单实例化的第一个参数(正如您在文章中正确地做的那样)是发布的数据,并且您没有更改表单的
\uuuu init\uuu
签名

其次,在
\uuuu init\uuuu
本身中,您引用了一个
用户
变量:但实际上您并没有从任何地方获得该变量。如果不从某处接收变量,就无法神奇地引用它们

因此,要修复这些错误,您需要如下更改init方法:

def __init__(self, *args, **kwargs):
    user = kwargs.pop('user')
    super(ContractForm, self).__init__(*args, **kwargs)
    self.fields['client'].queryset=Client.objects.filter(user=user)
并在视图中实例化表单,如下所示:

contractForm = ContractForm(user=request.user)
第三,尽管这与您发布的问题无关,但您永远不会在该表单上看到任何错误,因为您没有在post部分检查它是否有效-如果contractForm.is_valid()
,则需要检查
,如果没有,则进入最终的
呈现到\u响应
(需要在一个级别上取消关联)

另外,通过直接从
request.POST
设置模型,您忽略了创建表单的全部意义。您应该使用
contractForm.data
的内容来创建合同实例


最后,您应该调查ModelForm是否能更好地满足您的需求。

更改视图中表单的名称。现在看起来像这样

form = ContractForm(user=request.user)

它是有效的

无论哪种方式,Amaud都是正确的-QuerySet必须是实际的QuerySet对象。由于您的问题仍在继续,您能否更新代码示例以反映ContactForm类的当前状态?当您在页面上执行GET操作时,表单是否正常工作?另外,不要在开始时进行身份验证检查,而是检查将为您执行此操作的登录\u必需的装饰程序。@sdolan不,它不会对它产生任何影响。它仍然不会呈现表单。