Python 主页登录表单 Django
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20208562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
homepage login form Django
提问by Liondancer
I want to create a homepage with a header that asks to login with username/password and a login button to login. Currently, how I have my page set up is that pressing login will send me to a login page. I want to simply enter in the information and press "login" to login on the homepage of my site. How can I design my urls.pyand views.pyto perform login on the homepage?
我想创建一个带有标题的主页,要求使用用户名/密码登录和登录按钮登录。目前,我如何设置我的页面是按下登录会将我发送到登录页面。我想简单地输入信息并按“登录”登录我网站的主页。我如何设计我的urls.py并views.py在主页上执行登录?
I have a base.htmlthat is the template for my main page. Within the template, I made a login.htmlpartial view:
我有一个base.html这是我主页的模板。在模板中,我做了一个login.html局部视图:
<form action='/accounts/auth/' method='POST'> {% csrf_token %}
<div >
<label for='username'> Username </label>
<input type='text' name='Username' id='username'>
<label for='password'>Password </label>
<input type='password' name='Password' id='password'>
<input type='submit' value='login'>
</div>
</form>
I am a bit confused for the actionattribute as I'm not sure where to send that form data if I wanted to authorize login on the same page.
我对这个action属性有点困惑,因为如果我想在同一页面上授权登录,我不确定该将表单数据发送到哪里。
My views.py
我的意见.py
def login(request):
c = {}
c.update(csrf(request))
return render(request, 'login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username = username, password = password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
I'm not sure where to HttpResponseRedirectas well if logging in is all done on the home page.
HttpResponseRedirect如果登录全部在主页上完成,我也不确定在哪里。
Perhaps I can do a render(request,SomePartialView.html)instead of HttpResponseRedirect.
也许我可以做一个render(request,SomePartialView.html)而不是HttpResponseRedirect.
Here is my urls.py:
这是我的 urls.py:
url(r'^$', 'photoblog.views.login'), #displays login.html
url(r'^accounts/auth/$', 'photoblog.views.auth_view'), #authorize login
回答by suhailvs
I recommend django-registrationit is quite easy. there is an email verification too in it.
我建议django-registration它很容易。里面也有电子邮件验证。
you need an addition urlsay home:
你需要补充url说家:
url(r'^home/$', 'photoblog.views.home',name='home'),
.............
its views, homeaccess was limited to only logged-in users
它的views,home访问仅限于登录用户
from django.contrib.auth.decorators import login_required
@login_required(login_url='/') #if not logged in redirect to /
def home(request):
return render(request, 'home.html')
you don't need csrfin login.py
你不需要csrf在login.py
ie:
IE:
def login(request):
return render(request, 'login.html')
is enough, as renderwill pass csrf token.
就足够了,因为render将传递 csrf 令牌。
from django.core.urlresolvers import reverse
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username = username, password = password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect(reverse('home'))
else:
return HttpResponseRedirect('/accounts/invalid')
回答by Peter DeGlopper
If you just want to have a homepage with static content that handles logins, the Django built-in auth application can handle this with very little effort. You just need to bind a URL to django.contrib.auth.views.loginand probably one to django.contrib.auth.views.logout, write a login template and a post-logout template, then set a couple of setting variables.
如果您只想拥有一个包含处理登录的静态内容的主页,Django 内置的身份验证应用程序可以轻松处理此问题。您只需要绑定一个 URL 到django.contrib.auth.views.login,可能还有一个到django.contrib.auth.views.logout,编写登录模板和注销后模板,然后设置几个设置变量。
The full setup is documented here: https://docs.djangoproject.com/en/dev/topics/auth/default/#module-django.contrib.auth.views
完整设置记录在此处:https: //docs.djangoproject.com/en/dev/topics/auth/default/#module-django.contrib.auth.views
Here are the relevant bits from a working project of mine:
以下是我的一个工作项目中的相关部分:
urls.py
urls.py
# HomeView is a simple TemplateView that displays post-login options
urlpatterns = patterns('',
...
url(r'^myapp/$', HomeView.as_view(template_name='home.html'), name='home'),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),
...
)
settings.py
settings.py
from django.core.urlresolvers import reverse_lazy
...
LOGIN_URL = reverse_lazy('login')
LOGIN_REDIRECT_URL = reverse_lazy('home')
login.html
login.html
{% extends "base.html" %}
{% block head %}
<title>Login</title>
{% endblock %}
{% block body %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
logged_out.html
logged_out.html
{% extends "base.html" %}
{% block head %}
<title>Logged out</title>
{% endblock %}
{% block body %}
<p>You have been logged out. You may <a href="{% url 'login' %}">log back in</a>.</p>
{% endblock %}
I'm not showing my base.htmltemplate but I trust the pattern is obvious. If you want more than a bare login form there's no reason your login.htmltemplate couldn't be fancier. The names are default values, as documented for the views, but you could use other choices if you wanted to.
我没有展示我的base.html模板,但我相信这种模式很明显。如果您想要的不仅仅是一个简单的登录表单,那么您的login.html模板没有理由不能更漂亮。这些名称是默认值,如视图所记录的那样,但如果您愿意,您可以使用其他选择。
That's all you need for the basic behavior. If you wrap your views with the login_requireddecorator as described in the docs, it will redirect to your login page any time a non-authenticated user tries to access one of your views. Or, if you're using class-based views, use @method_decorator(login_required)as documented here. Two more snippets from my project:
这就是基本行为所需的全部内容。如果您login_required按照文档中的说明使用装饰器包装您的视图,则只要未经身份验证的用户尝试访问您的视图之一,它就会重定向到您的登录页面。或者,如果您使用基于类的视图,请@method_decorator(login_required)按照此处的说明使用。我的项目中的另外两个片段:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class HomeView(TemplateView):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
@login_required
def report_for_group(request, group_id):
...
The docs include discussions of some more complicated setups, should you need them.
如果您需要,这些文档包括对一些更复杂设置的讨论。
回答by Goran
Using Django 1.11.I had the same problem just now, here's what worked for me...
使用 Django 1.11。我刚才遇到了同样的问题,这对我有用...
Import the login view class from the built in auth app and pass in your template file via the template_namekwarg.
从内置的 auth 应用程序导入登录视图类,并通过template_namekwarg传入您的模板文件。
In urls.py:
在 urls.py 中:
from django.contrib.auth.views import LoginView
app_name = 'yourapp'
urlpatterns = [
url(r'^$', LoginView.as_view(template_name='yourapp/index.html'), name="index"),
]
And in your view you can use the form variable to render out your form. In my case I use bootstrap so.
在您的视图中,您可以使用表单变量来呈现您的表单。在我的情况下,我使用引导程序。
In index.html:
在 index.html 中:
{% extends 'base.html' %}
{% loads bootstrap %}
{% block content %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button "Login" button_type="submit" button_class="btn-primary" %}
{# Assumes you setup the password_reset view in your URLconf #}
<p><a href="{% url 'password_reset' %}">Lost password?</a></p>
</form>
{% endblock content %}
回答by armin
I found the solution.
我找到了解决方案。
first, customize login and logout views:
首先,自定义登录和注销视图:
views.py
视图.py
def login_user(request):
logout(request)
username = password = ''
form1 = RegistrationForm()
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("redirect any whre u want")
return render(request, 'Write login templaye address')
def logout_user(request):
user = request.user
logout(request, user)
return redirect("redirect any whre u want")
Then in your base.html you should do like this:
然后在你的 base.html 你应该这样做:
base.html
基本文件
<form method="post" action="/user/login/" novalidate>
{% csrf_token %}
<input class="form-control" id="id_username" name="username" placeholder=""
required="" type="text"
style="">
</div>
<div class="form-group">
<span class="material-icons" style=""
>lock</span>
<input class="form-control" id="password1" name="password" style="" autofocus=""
placeholder=""
required=""
type="password">
</div>
<button class="btn btn-primary" type="submit" style=""></button>
</div>
</form>
And login.html
和登录.html
<form method="post" action="/user/login/">
{% csrf_token %}
<div class="form-group">
<p>
<label for="id_username">username</label>
<input class="form-control" id="id_username" name="username" autofocus="" required="" type="text">
</p>
<p>
<label for="id_password">password</label>
<input class="form-control" id="id_password" name="password" autofocus="" required="" type="password">
</p>
<button type="submit">login</button>
</div>
</form>
urls.py
网址.py
url(r'^login/$', views.login_user, name='login'),
url(r'^logout/$', views.logout_user),
Actually you take inputs in homepage and give them into login page its good for input error handling.
实际上,您在主页中输入并将它们输入登录页面,这对输入错误处理很有帮助。
回答by Md. Mizanur Rahman Khan
You can use Django's built in log in form. It is quit easy and efficient.And it will give you some features like form validation check.
您可以使用 Django 的内置登录表单。它非常简单和高效。它会给你一些功能,比如表单验证检查。
in urls.py:
在 urls.py 中:
url(r'^login/$',views.loginView,name='login'),
in views.py:
在views.py中:
from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
def loginView(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('/website/profile/')
else:
form = AuthenticationForm()
return render(request, 'website/login.html', {'form': form})
in html page:
在 html 页面中:
<form method="post">
{% csrf_token %}
{{form.as_p}}
<p><input type="submit" value="Log in"></input></p>

