gpt4 book ai didi

Django 表单不呈现

转载 作者:行者123 更新时间:2023-12-01 15:16:16 26 4
gpt4 key购买 nike

我在 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 看起来像这样:

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

那么为什么表单不呈现?


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

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

最佳答案

forms.ModelChoiceFieldqueryset 参数应该是一个查询集。它应该是:

self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user=user))

__init__() 方法中覆盖它之前,你必须先在你的表单中声明它:

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

关于Django 表单不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com