有人能告诉我如何避免错误信息显示2次吗?我想保留最上面的错误消息,但显示为红色。
https://files.slack.com/files-pri/T07EFKXHR-F058SR427RA/image.png
html:
<form hx-post="{{ request.path }}" class="modal-content p-4" enctype="multipart/form-data">
<div class="modal-header">
<h5 class="modal-title">Ingresa tu usuario y clave</h5>
</div>
{% csrf_token %}
{{ login_form.as_p }}
{% if login_form.errors %}
<ol class="">
{% for field_errors in login_form.errors.values %}
{% for error in field_errors %}
<li class="text-danger"><strong>{{ error|escape }}</strong></li>
{% endfor %}
{% endfor %}
</ol>
{% endif %}
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Ingresar</button>
</div>
</form>
form.py:
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Nombre de usuario'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Contraseña'}))
view.py:
def login_view(request):
if request.method == 'POST':
login_form = LoginForm(request, data=request.POST)
print("### Request is post")
if login_form.is_valid():
print("### Request is VALID")
username = login_form.cleaned_data.get('username')
password = login_form.cleaned_data.get('password')
print("User name", username, "type: ", type(username))
print("Pass", password, "type: ", type(password))
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
return HttpResponse(status=204, headers={'HX-Trigger': 'user_logged_in'})
else:
return render(request=request, template_name="account/email/login_form.html",
context={'login_form': login_form, 'errors': login_form.errors})
else:
login_form = LoginForm(request)
context = {
"login_form": login_form,
}
return render(request=request, template_name="account/email/login_form.html",
context={'login_form': login_form, 'errors': login_form.errors})
更新1:
不显式渲染HTML中的错误,让我没有任何错误。
可能与HTMX使用有关?
<form hx-post="{{ request.path }}" class="modal-content p-4" enctype="multipart/form-data">
<div class="modal-header">
<h5 class="modal-title">Ingresa tu usuario y clave</h5>
</div>
{% csrf_token %}
{{ login_form.as_p }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Ingresar</button>
</div>
</form>
图片:
1条答案
按热度按时间qxsslcnc1#
Django默认在
{{ login_form.as_p }}
中呈现错误。如果需要显式地呈现错误,则很容易出错,因为很容易忘记这一点。所以有一次呈现错误,第二次呈现错误是因为你自己通过块
{% if login_form.errors %} ... {% endif %}
显式地做了这件事。