[英]Django form does not work or CSRF_token aborted
Hello I am making Django App.您好,我正在制作 Django 应用程序。 I have a problem with my login form.我的登录表单有问题。 Whenever I want to login, form does not do anything or it throws csrf token error.每当我想登录时,表单不会执行任何操作或抛出 csrf 令牌错误。 Views:意见:
def loginView(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"You successfully logged in {username}")
return redirect('home-page')
else:
form = AuthenticationForm()
return render(request, 'shop/login.html', {'form': form})
HTML TEMPLATE: HTML 模板:
{% extends 'shop/base.html' %}
{% block content %}
<div class = "form-container">
<form class="form" method="POST">{% csrf_token %}
<label for="username">Email:</label>
{{form.username}}
<label for="password">Passoword:</label>
{{form.password}}
<button type="submit">Login</button>
</form>
</div>
{% endblock content %}
you have to check whether user existed or not in db if yes then login and redirect if not throw error or redirect on other page您必须检查用户是否存在于数据库中,如果是,则登录并重定向,如果不抛出错误或重定向到其他页面
def my_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect('path')
else:
return redirect('path')
else:
return redirect('path')
else:
form = AuthenticationForm()
return render(request, "shop/login.html", {'form': form})
still get error add the complete traceback & i will also suggest you to read the full documentation of django https://docs.djangoproject.com/en/3.2/ref/contrib/auth/仍然出现错误添加完整的回溯 & 我还建议您阅读 django https://docs.djangoproject.com/en/3.2/ref/contrib/auth/的完整文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.