我目前正在通过以下教程:https://www.tutorialspoint.com/django/django_form_processing.htm
我是django的新手,之前的教程是我在django中唯一的体验,因此显然没什么可说的。当我尝试使用表单登录时,收到消息:您是:未登录,但是我应用的登录凭据与我在教程开头创建超级用户时应用的相同,所以我觉得他们应该有效。这是我的文件:
forms.py
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(max_length = 100)
password = forms.CharField(max_length = 100)
的login.html
<html>
<body>
<form name = "form" action = "{% url "login" %}"
method = "POST" >{% csrf_token %}
<div style = "max-width:470px;">
<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "Identifiant" name = "username" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<input type = "password" style = "margin-left:20%;"
placeholder = "password" name = "password" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<button style = "border:0px; background-color:#4285F4; margin-top:8%;
height:35px; width:80%;margin-left:19%;" type = "submit"
value = "Login" >
<strong>Login</strong>
</button>
</center>
</div>
</form>
</body>
</html>
urls.py (在myapp文件夹中)
from django.conf.urls import url
from django.views.generic import ListView, TemplateView
from myapp.views import hello, viewArticle, crudops, login
from myapp.models import Dreamreal
urlpatterns = [
url(r'^hello/', hello, name = 'hello'),
url(r'^article/(\d+)/', viewArticle, name = 'article'),
url(r'^crudops/', crudops, name = "crudops"),
url(r'^dreamreals/', ListView.as_view(model = Dreamreal, template_name = "dreamreal_list.html")),
url(r'^connection/', TemplateView.as_view(template_name = "login.html")),
url(r'^login/', login, name = 'login'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Dreamreal
import datetime
from myapp.forms import LoginForm
def hello(request):
today = datetime.datetime.now().date()
return render(request, "hello.html", {"today":today, "days": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]})
def viewArticle(request, articleId):
text = "Displaying article: %s " %articleId
return HttpResponse(text)
def crudops(request):
#Read All Entries
objects = Dreamreal.objects.all()
text = "Here are all the entries in the Dreamreal Database"
for obj in objects:
text += "<br/>" + obj.website + ", " + obj.name + "<br/>"
return HttpResponse(text)
def login(request):
username = "Not Logged In"
if request.method == "POST":
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data["username"]
else:
MyLoginForm = LoginForm()
return render(request, "loggedin.html", {"username": username})
............................................... ..............................
非常感谢任何帮助。
答案 0 :(得分:0)
表单和模板上的字段名称需要匹配。因为你有
<input type = "text" style = "margin-left:20%;"
placeholder = "Identifiant" name = "username" />
使用name = username
,您需要确保您的表单使用该字段名称。
class LoginForm(forms.Form):
username = forms.CharField(max_length = 100)
password = forms.CharField(max_length = 100)