2-10[11] 수작업으로 폼 작성하기 - {% for field in form %} 질문
현재 아래의 코드를 보고있다가 구조가 이해가 안가서 질문드립니다.
장고 도큐멘테이션의 설명에서는
form 객체에서 form.errors를 사용하면 key가 속성, value가 에러메시지인 딕셔너리를 반환하는데요.
아래의 코드라면
is_valid()가 false면
form.errors를 할 경우, { 'subject' : ['에러 메시지'], 'content' : ['에러메시지']} 형태로 반환된다고 생각했습니다. 그런데 아래에 보면 {% for field in form %}를 하면 field에는 subject,content라는 key가 반복문을 통해 순서대로 오고 {% if field.errors %}에서 true라면 {{ field.label }}, {{ field.errors }}가 출력되는데요.
제가 이해한 내용으로라면 이때 field가 key니까, if subject.errors, content.errors 식으로 작동되는건데
이 subject, content는 form의 field인데도 errors를 사용할 수 있는 건가요?
subject.errors일 경우 form.errors에서 content부분만을 제외하고 { 'subject' : ['에러 메시지']}를 반환하는건지..구조가 어떻게 되는지 이해가 안되서 질문드립니다.
마찬가지로 {{ field.label }}가 어떻게 나오는지도 궁금합니다. 개인적으로는 {{ form.label }}이라고 생각했었는지라..
그리고 현재 아래의 2개의 파일의 코드가 있는데, 양쪽 다 label이 설정되어 있습니다.
왜 2개 다 작성하는지도 잘 이해가 안갑니다.
현재 html 탬플릿 파일 코드
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h5 class="my-3 border-bottom pb-2">질문등록</h5>
<form method="post" class="post-form my-3">
{% csrf_token %}
<!-- ------------------------------- [edit] -------------------------------- -->
<!-- 오류표시 Start -->
{% if form.errors %}
<div class="alert alert-danger" role="alert">
{% for field in form %}
{% if field.errors %}
<strong>{{ field.label }}</strong>
{{ field.errors }}
{% endif %}
{% endfor %}
</div>
{% endif %}
<!-- 오류표시 End -->
<div class="form-group">
<label for="subject">제목</label>
<input type="text" class="form-control" name="subject" id="subject"
value="{{ form.subject.value|default_if_none:'' }}">
</div>
<div class="form-group">
<label for="content">내용</label>
<textarea class="form-control" name="content"
id="content" rows="10">{{ form.content.value|default_if_none:'' }}</textarea>
</div>
<!-- ----------------------------------------------------------------------- -->
<button type="submit" class="btn btn-primary">저장하기</button>
</form>
</div>
{% endblock %}
현재 forms.py 코드
from django import forms
from pybo.models import Question
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ["subject", "content"]
labels = {
"subject": "제목",
"content": "내용",
}
**장고 도큐멘테이션 설명** url:https://docs.djangoproject.com/en/3.2/ref/forms/api/#django.forms.Form.errors
Form.errors
Access the errors attribute to get a dictionary of error messages:
f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
In this dictionary, the keys are the field names, and the values are lists of strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.
You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors.
The validation routines will only get called once, regardless of how many times you access errors or call is_valid(). This means that if validation has side effects, those side effects will only be triggered once.
HJ 님 633
M 2021년 7월 15일 4:00 오후
1개의 답변이 있습니다. 1 / 1 Page
{% for field in form %}
에서 field는 폼에 정의한 필드를 의미합니다.
따라서 field.label 은 폼 필드의 label 속성을 의미합니다.
도움이 되셨기를 바랍니다.
박응용 님
2021년 7월 15일 3:49 오후