多くの人が既にこのエラーに遭遇していますが、私がしようとしているのは具体的で、他の質問に対する回答は役に立ちません。 私はDjangoを初めて使いました。名前、姓、電子メール、パスワードの各フィールドを使ってフォームを作成しようとしています。フォームが送信された後、それらをすべてファイルに書きたいと思います。私はUserオブジェクトを持っておらず、実際にサインインページを作ろうとはしていません。ちょうどtxtファイルに何を書き込むことができるのか見たいだけです。Django AttributeError:フォームオブジェクトに属性がありませんx
だから、私はurls.pyで、これをしなかった:
url(r'^file/$', views.employee, name='employee')
次にviews.pyに:
def employee(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
with open('employee.txt', 'w') as f:
myfile = File(f)
myfile.write('%s ... %s ... %s ... %s ' % form.first_name % form.last_name % form.email % form.password)
return render(request, 'blog/employee_thanks.html')
else:
form = EmployeeForm
return render(request, 'blog/employee.html', {'form': form})
ので、私はforms.pyでEmployeeFormを持っている:
class EmployeeForm(forms.Form):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput())
と関連するhtmlファイルは、 employee.html:
です。{% extends 'blog/base.html' %}
{% block content %}
<h1>Employee Sign-in</h1>
<h3>Please sign in with your Credentials</h3>
<form method="post" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-primary">Sign in</button>
</form>
{% endblock %}
とemployee_thanks.html:
{% extends 'blog/base.html' %}
{% block content %}
<div class="container">
<h1>Thank you for signing in!</h1>
<h3>You will get an email with questions soon.</h3>
</div>
{% endblock %}
そして最後に、問題のエラーは:
AttributeError at /file/ 'EmployeeForm' object has no attribute 'first_name' Request Method: POST Request URL: http://localhost:8000/file/ Django Version: 1.10 Exception Type: AttributeError Exception Value:
'EmployeeForm' object has no attribute 'first_name'
私はこの問題を推測しているforms.pyとviews.pyの間のどこかですが、私はそれが何であるか分かりません。 私は趣味としてこれをやっているので、質問が愚かであれば、あまりにも厳しくしないでください。 ありがとうございます。
おかげで、これは非常に洞察に満ちました。 私はフォローアップの質問があります。フォームを2回送信すると、2番目の入力が.txtファイルの最初の入力を上書きするように見えます。行の中で "w"以外の何かを使うことになっていますか?open( 'employee.txt'、 'w')をfとしていますか? 更新: "追加"として "a"を使用していたはずです。誰かがそれを必要とする場合に備えてこれを残し、また感謝を示す。 –
@MiodragNisevic:そうです、 '' w ''がファイルを上書きするので '' a ''を使います。各書式の提出のフィールドが1行に表示されるように、各書込みの最後に改行を追加することができます。 – mhawke