1、创建form.py
进行注册用户系统表单的建立
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
2、在views.py
中引入用户验证模块(系统自带)
from django.contrib.auth import authenticate, login
from firstapp.forms import LoginForm
此处firstapp是你建立的应用名字
views.py中代码如下:
def index_login(request):
context = {}
if request.method == "GET":
form = LoginForm
if request.method == "POST":
form = LoginForm(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(to='index')
else:
return HttpResponse('Not a user')
context['form'] = form
return render(request, 'login.html', context)
3、在前端页面显示用户名
当操作完成后,在前端使用
request.user.is_authenticated
对登录的user进行用户名和密码的验证,并使用request.user.username
进行用户名的显示。
{% if request.user.is_authenticated %}
{{ request.user.username }}
{% else %}
{% endif %}```


#4、自定义用户头像
在models.py中添加
from django.contrib.auth.models import User
class UserProfile(models.Model):
belong_to = models.OneToOneField(to=User, related_name="profile1")
profile_image = models.ImageField()
在setting.py中添加上传的目录
MEDIA_URL = '/upload/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
在urls.py中添加:
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
完毕后,在模板中
{% if request.user.is_authenticated %}
{% if request.user.profile1.profile_image %}
{% else %}
{% endif %}
{{ request.user.username }}
{% else %}
{% endif %}
在后台上传头像后,显示结果如下:


#5、注册与登出
使用Django自带表格
`from djagno.contrib.auth.forms import UserCreationForm, AuthenticationForm`
这是django自带表格,分别为创建用户表格和验证用户表格
def index_login(request):#登录验证表单
context = {}
if request.method == "GET":
form = AuthenticationForm
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
login(request, form.get_user())
return redirect(to='index')
context['form'] = form
return render(request, 'login.html', context)
def index_register(request):#创建用户表单
context = {}
if request.method == "GET":
form = UserCreationForm
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(to='list')
context['form'] = form
return render(request, 'login.html', context)
```
对urls.py进行操作,写出相应url
from django.contrib.auth.views import logout
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name="index"),
url(r'^detail/(?P\d+)/$', detail, name="detail"),
url(r'^comment/(?P\d+)/$', comment, name="comment"),
url(r'^login/$', index_login, name="login"),
url(r'^register/$', index_register, name="register"),
url(r'^logout/$', logout,{'next_page': '/register'}, name="logout"),
]
此处使用系统自带的logout模块
引入刚才在views.py中的index_login, index_register并写入相应的url。
在前端登录代码如下:
Logout