无法在我的应用程序中登录。我在views.py中写道
from django.shortcuts import render,redirect
from django.urls import reverse
from app.forms import RegisterForm,LoginForm
from app.models import Data
from app.forms import DataForm
from django.db.models import Q
def index(request):
data = Data.objects.order_by('-created_at')
form = RegisterForm()
loginform = LoginForm()
dataform = DataForm()
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
在index.html
<section id="top">
{% if user and not user.is_anonymous %}
<p>Hello</p>
<h3>{{ user.username }}</h3>
{% else %}
<form action="{% url 'app:index' %}" method="POST">
{{ loginform.non_field_errors }}
{% for field in loginform %}
{{ field }}
{{ field.errors }}
{% endfor %}
<button type="submit">LOGIN</button>
{% csrf_token %}
</form>
{% endif %}
</section>
forms.py
from django import forms
from django.contrib.auth.forms import (
AuthenticationForm
)
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
field.widget.attrs['placeholder'] = field.label
在儿童应用程序的urls.py中
from django.urls import include, path
from . import views
from django.contrib.auth.views import login
app_name = 'app'
urlpatterns = [
path('index', views.index,name='index'),
]
在父级应用的urls.py中
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/',include('app.urls') ),
]
当我从loginform登录时,如果{% if user and not user.is_anonymous %}
的语句不为真。但是,当我在管理站点中登录时,该语句为true。当我按下LOGIN按钮时,没有错误发生。我真的无法理解是错误的。我该如何解决?
答案 0 :(得分:2)
提交index
请求时,您的POST
视图不执行任何操作。它只是初始化空表格并返回它们。您需要实际处理提交的数据,对用户进行身份验证并调用login
方法:
def index(request):
if request.method == 'POST':
loginform = LoginForm(request, data=request.POST)
if loginform.is_valid(): # this authenticates the user
user = loginform.get_user()
# redirect to success view or just render index.html
return render(request, 'index.html', {'user': user})
# else not needed, we go to the end and return the form with errors
else: # request method is 'GET'
loginform = LoginForm()
dataform = ...
...
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})