我有一个基于类的视图,它显示登录表单。问题是我无法显示错误消息。我试图在URL的参数中发送错误消息,以在HTML模板文件中显示该错误消息。但这是行不通的。
到目前为止,这是我的代码:
表格
# a class which act as a view - it displays the login-form
class LoginForm(AuthenticationForm, BaseLoginView):
username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
def get_context_data(self, **kwargs):
context = super(LoginForm, self).get_context_data(**kwargs)
context['error'] = ''
return context
urls.py
urlpatterns = [
path('login/', views_auth.LoginView.as_view(form_class=LoginForm, redirect_authenticated_user=True), name='login'), # login-page
]
views.py
# login functionality for the user
def custom_user_login(request):
if request.method == 'GET':
error_message = ''
return redirect('home')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
error_message = ''
# if the username & password is correct
user = authenticate(request, username=username, password=password)
if user is not None:
# Redirecting to the required login according to user type (admin / regular-user)
if user.is_superuser or user.is_staff:
login(request, user)
return redirect('admin_section/')
else:
login(request, user)
return redirect('/')
# display error message
else:
base_url = reverse('login') # /login/
query_string = urlencode({'error': 'The username & password combination are incorrect - please try again!'}) # error=The username & password combination are incorrect - please try again!
url = '{}?{}'.format(base_url, query_string) # /login/?error=The username & password combination are incorrect - please try again!
return redirect(url) # redirects to the login page with an error-message
login.html
<!-- error message -->
<div id="error" class="alert alert-danger alert-dismissible" role="alert">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
{{ view.error }}
</div>
<form method="post" action="{% url 'custom_login' %}">
{% csrf_token %}
{% for field in form %}
<div class="form-group row">
{{ field.errors }}
<label for="{{ field.name }}" class="col-md-4 col-form-label text-md-right">{{ field.label }}</label>
<div class="col-md-6">
{{ field }}
</div>
</div>
{% endfor %}
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Login
</button>
</div>
</form>
您无需手动收集,添加到上下文中并显示错误。表单本身存储错误。field.errors
在模板中调用时,您已经遇到了特定于字段的错误,但是您也可以使用来获取非特定于字段的错误form.errors
。有关更多详细信息,请参见关于表单错误的Django文档。
顺便说一句,您可以在模板中显示来自url的GET变量。只需使用{{ request.GET.error }}
。同样,无需在URL本身中编码错误消息。这不是解决此问题的好方法,Django已经为您解决了这一问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句