Form.is_valid()始终返回false,并且它从不显示任何类型的错误。以下是forms.py,views.py和template / transaction_add_page.html
的代码段表格
class TransactionForm(forms.Form):
account = forms.ModelChoiceField(queryset=Account.objects.none())
transactions = forms.CharField(widget=forms.Textarea(attrs={'rows':'10', 'cols':'70'}))
def __init__(self, user, *args, **kwargs):
super(TransactionForm, self).__init__(*args, **kwargs)
self.fields['account'].queryset = Account.objects.filter(user=user)
def clean_account(self):
if 'account' in self.cleaned_data:
account = self.cleaned_data['account']
return account
raise forms.ValidationError('Please select an account.')
def clean_transactions(self):
if 'transactions' in self.cleaned_data:
transactions = self.cleaned_data['transactions']
return transactions
raise forms.ValidationError('At-least one transaction is required.')
查看
@login_required
def transaction_add_page(request):
if request.method == 'POST':
form = TransactionForm(request.POST)
if form.is_valid():
variables = RequestContext(request, {'account': form.clean_account(), 'transactions': form.clean_transactions()})
return render_to_response('transaction_confirm_page.html', variables)
form = TransactionForm(request.user)
variables = RequestContext(request, {'form': form})
return render_to_response('transaction_add_page.html', variables)
模板
{% extends "base.html" %}
{% block title %}Add Transactions{% endblock %}
{% block head %}Add Transactions{% endblock %}
{% block content %}
<form method="post" action="." >
{{ form.non_field_errors }}
{{ form.errors }}
{% for field in form %}
<div>
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<input type="submit" value="Add Transactions" />
</form>
{% endblock %}
答案 0 :(得分:2)
如果在初始化程序中设置了用户参数,则需要使用它。
if request.method == 'POST':
form = TransactionForm(user=request.user, data=request.POST)