gpt4 book ai didi

python - form.is_valid() 总是返回 false

转载 作者:行者123 更新时间:2023-12-01 06:12:07 27 4
gpt4 key购买 nike

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

最佳答案

如果您在初始化程序上设置了用户参数,则需要使用它。

if request.method == 'POST':
form = TransactionForm(user=request.user, data=request.POST)

关于python - form.is_valid() 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5254470/

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