1,cookie技术
视图views里面:
def index(request):
#获取请求中的cookie
num = request.COOKIES.get('num')
if num:
num = str(int(num) + 1)
else:
num = '1' response = render(request, 'teacher/index.html', context={'num':num})
#设置cookie
response.set_cookie('num', num) return response 2,session技术
def index(request):
#获取请求中的cookie
name = request.session.get('name') return render(request, 'teacher/index.html', context={'name': name})
def login(request): if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
if username == 'xinlan' and password == '123456':
#首页检查有没有name,没有name就显示未登录,有name就显示用户名
request.session['name'] = username
request.session.set_expiry(10) #过期时间
#跳转到首页面
return redirect(reverse('teacher:index')) return render(request, 'teacher/login.html')
安全退出
views:
def logout(request):
request.session.flush()
return redirect(reverse('teacher:index'))
index:
<a href="{% url 'teacher:logout' %}">安全退出</a>
urls:
path('logout/', views.logout, name='logout'),
3,form表单
app--teacher 下新建forms.py文件
4,模型表单
过滤器
@register.simple_tag()
def add_class(field, class_str): return field.as_widget(attrs={'class': class_str}) models:
class Student(models.Model):
name = models.CharField('姓名', max_length=20)
age = models.SmallIntegerField(default=0)
sex = models.SmallIntegerField('性别', default=1)
qq = models.CharField(max_length=20, unique=True, null=True, error_messages={'unique':'qq号码重复!'})
phone = models.CharField(max_length=20, unique=True, null=True)
grade = models.ForeignKey('Grade', on_delete=models.SET_NULL, null=True)
c_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
e_time = models.DateTimeField(verbose_name="编辑时间", auto_now=True)
is_deleted = models.BooleanField(default=False) def __str__(self):
return '%s-%s' % (self.name, self.age)