跟老齐学Django 2:用户管理

模板和静态文件:./mysite/setting.py    都配置在网站根目录下

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),],  #制定路径
        'APP_DIRS': False,  #不按应用目录下
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
	os.path.join(BASE_DIR, "static"),
)

$ python3 manage.py startapp account  实现用户登录、退出、注册等功能

subl account/forms.py 表单

In [1]: from account.forms import LoginForm

In [2]: login_form = LoginForm()

In [3]: print(login_form)
<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" required id="id_username"></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" required id="id_password"></td></tr>

subl account/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm 

# Create your views here.
def user_login(request):
	if request.method == "POST":
		login_form = LoginForm(request.POST)
		if login_form.is_valid():
			cd = login_form.cleaned_data
			user = authenticate(username=cd['username'], password=cd['password'])
			if user:
				login(request, user)
				return HttpResponse("Welcome You.")
			else:
				return HttpResponse("Sorry.")
		else:
			return HttpResponse("Invalid login")

	if request.method == "GET":
		login_form = LoginForm()
		return render(request, "account/login.html", {"form":login_form})

def user_logout(request):
	logout(request)
	return render(request, "account/logout.html")

https://docs.djangoproject.com/en/1.10/topics/auth/default/

account/forms.py

class RegistractionForm(forms.ModelForm):
	password = forms.CharField(label="Password", widget=forms.PasswordInput)
	password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput)

	class Meta:
		model = User
		fields = ("username", "email")

	def clean_password2(self):
		cd = self.cleaned_data
		if cd['password'] != cd['password2']:
			raise forms.ValidationError("passwords do not match.")
		return cd['password2']

account/models.py 增加注册信息

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
	user = models.OneToOneField(User, unique=True, on_delete=models.DO_NOTHING)
	birth = models.DateField(blank=True, null=True)
	phone = models.CharField(max_length=20, null=True)

	def __str__(self):
		return 'user {}'.format(self.user.username)

$ python3 manage.py makemigrations account

$ python3 manage.py migrate account

第三方登录https://github.com/omab/django-social-auth

https://blog.csdn.net/asd131531/article/details/42457389?locationNum=10&fps=1

关于密码

pip3 install django-password-reset

account/models.py

class UserInfo(models.Model):
	user = models.OneToOneField(User, unique=True, on_delete=models.DO_NOTHING)
	school = models.CharField(max_length=100, blank=True)
	company = models.CharField(max_length=100, blank=True)
	profession = models.CharField(max_length=100, blank=True)
	address = models.CharField(max_length=100, blank=True)
	aboutme = models.TextField(blank=True)

	def __str__(self):
		return 'user {}'.format(self.user.username)

$ python3 manage.py makemigrations account

$ python3 manage.py migrate account

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值