2017-02-13 7 views
-1

많은 사람들이 이미이 오류가 발생했음을 알고 있습니다. 그러나 내가하려는 것은 구체적이며 그 다른 질문에 대한 답변은 도움이되지 않습니다. Django를 처음 사용하며 이름, 성, 이메일 및 비밀번호 필드가있는 양식을 만들려고합니다. 양식을 제출 한 후에 모든 파일을 파일로 작성하고 싶습니다. 저는 User 객체가 없으며 실제로 로그인 페이지를 만들려하지 않고, txt 파일에 어떻게 쓸 수 있는지보고 싶습니다.Django AttributeError : 폼 객체에는 속성이 없습니다. x

그래서, 난 urls.py에, 이런 짓을 :

views.py에서 다음
url(r'^file/$', views.employee, name='employee') 

:

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

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이

및 해당 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 사이 어딘가에이지만, 나는 그것이 무엇인지 모릅니다. 나는 취미로서 이것을하고 있기 때문에, 질문이 멍청하다면 너무 가혹하지 마십시오. 미리 감사드립니다 :)

답변

1

form 개체 인스턴스는 기본 개체 인스턴스의 특성이므로 first_name, last_name 등의 특성을 갖지 않습니다.

대신,이 같은 FIRST_NAME에 액세스 할 수 있습니다

form.cleaned_data.get("first_name") 

당신은 당신의 코드에서 오류 몇 가지가 있습니다 django forms and accessing attributes in this link

1

에 대한 자세한 내용을보실 수 있습니다.

첫 번째는 양식 필드가 Form 인스턴스의 속성이 아니라는 것입니다. form.is_valid()으로 확인한 후에 form.cleaned_data 사전을 사용하여 입력란에 액세스 할 수 있습니다 (예 : 보다 안전하게

form.cleaned_data['first_name'] 

또는 : 필드 형태로 존재하지 않는 경우 예외를 발생시키는 대신 빈 문자열을 반환합니다

form.cleaned_data.get('first_name', '') 

.


번째 오류 구문 포맷 문자열이 잘못된 것입니다

myfile.write('%s ... %s ... %s ... %s ' % form.first_name % form.last_name % form.email % form.password) 

는 같아야

값 터플은
myfile.write('%s ... %s ... %s ... %s ' % (form.cleaned_data['first_name'], form.cleaned_data['last_name'], form.cleaned_data['email'], form.cleaned_data['password'])) 

문자열로 치환 될해야 사용하십시오. 그러나이 같은 사전을 전달하여 단순화 할 수 있습니다

myfile.write('%(first_name)s ... %(last_name)s ... %(email)s ... %(password)s' % form.cleaned_data) 

더 나은 아직, 지금 선호하는 방법이다 str.format()를 사용

myfile.write('{first_name} ... {last_name} ... {email} ... {password} '.format(**form.cleaned_data)) 
+0

감사합니다, 이것은 매우 통찰력이 있었다. 나는 두 번째 입력이 .txt 파일의 첫 번째 입력을 덮어 쓰는 것처럼 보입니다. 내가 줄에서 "w"와 다른 것을 사용하기로되어 있나? open ('employee.txt', 'w') f로? 업데이트 : "추가"로 "a"를 사용해야합니다. 다른 사람이 필요로하는 경우를 대비해서 이것을 남겨두고 감사를 표하십시오. –

+0

@MiodragNisevic : 맞습니다.''w ''가 파일을 덮어 쓰기 때문에''a ''를 사용하십시오. 각 양식 제출의 필드가 한 행에 표시되도록 각 쓰기 끝에 새 행을 추가 할 수 있습니다. – mhawke

관련 문제