Django Form未渲染 [英] Django Form not rendering

查看:122
本文介绍了Django Form未渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

forms.py中具有以下形式:

I have the following form in 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如下所示:

But the form won't render in the browser. All that shows up is the submit button. My HTML looks like this:

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

那么为什么不渲染表单?

So why won't the form render?

编辑
我摆脱了需要用户的自定义客户端字段,但该字段仍不会呈现。我认为这可能会有所帮助。
因此,表单可以使用此类:

EDIT I have got rid of the custom client field requiring the user and it still won't render. I thought this might help. So a form could use this class:

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


推荐答案

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

Change the name of the forms in the view. It now looks like this

form = ContractForm(user=request.user)

它有效。

这篇关于Django Form未渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆