Lanms Blog

Django-Form和ModelForm-Cookie-Session
Publish: 2019/3/21   

widget = forms.HiddenInput()   # 表单小组件, 隐藏字段
initial = {}  添加表单初始数据   # 41 行
调用 is_valid 时, 写的额外的验证时也会执行
redirect('url')   重定向, 重新加载

Form 和 ModelForm

# Form
class CarRecordForm(forms.Form):

    carno = forms.CharField(max_length=7 ,label='车牌号',
                            error_messages={})
    case = forms.CharField(max_length=50, label='违章原因')
    punish = forms.CharField(max_length=50, required=False, 
                             label='处罚方式') #required 属性False可以不填

def add(request):

    if request.method == 'GET':
        errors = []
        f = CarRecordForm()
    else:
        f = CarRecordForm(request.POST)
        if f.is_valid():
            a = f.cleaned_data # 获得输入的纯数据, 字典样式
            Car(**a).save()
            f = CarRecordForm()
        else:
            errors = f.errors.values()  # 所有的错误信息
    return render(request, 'add.html',
                  context={'f': f, 'errors': errors})



# ModelForm
class CarRecordForm(forms.ModelForm):

    carno = forms.CharField(max_length=7 ,label='车牌号', error_messages={})
    case = forms.CharField(max_length=50, label='违章原因')
    punish = forms.CharField(max_length=50, required=False,
                             label='处罚方式') #required 属性False可以不填

    class Meta:
        model = CarRecord   # 指定模型对应的model, 在models.py文件中
        fields = ('carno', 'case', 'punish') # 与数据库模型对应的项目


def add(request):

    if request.method == 'GET':
        errors = []
        f = CarRecordForm()# 添加初始化字符 initial = {}添加表单初始数据
    else:
        f = CarRecordForm(request.POST)
        if f.is_valid():
            f.save()
            return redirect('/search2')  # 重定向,跳转到search2
        else:
            errors = f.errors.values()  # 所有的错误信息
    return render(request, 'add.html', context={'f': f, 'errors': errors})

HTTP无状态协议

用户跟踪和识别

  1. 隐藏域, 隐式表单域, 在提交表单是添加额外的隐藏字段, 表明用户身份
  2. url重写, 在 ? 后面 添加额外的键值对, 向服务器提供身份标识, 不能超过2048字节
  3. Cookie , 放在请求头里面, 服务器用来识别用户身份的标识, 禁用后服务器无法识别,
自建项目创建Cookie
def search(request):
    current_time = datetime.datetime.now().ctime()
    last_vist_time = request.COOKIES.get('last_vist_time', 
                                         current_time)

    if request.method == 'GET':
        ctx = {'show_result': False, 'last_time': last_vist_time}
        response = render(request, 'search.html', ctx)
        response.set_cookie('last_vist_time', current_time,
                            max_age=1209600)
        return response

对数据进行处理

forms.ModelForm额外添加条件验证数据

session

拦截过滤器模式

session应用

views.py

from datetime import datetime

from django.shortcuts import render, redirect

from cart.models import Goods


class CartItem(object):

    def __init__(self, no, goods, amount=1):
        self.no = no
        self.goods = goods
        self.amount = amount

    @property
    def total(self):

        return self.goods.price * self.amount


class ShoppingCart(object):

    def __init__(self):
        self.num = 1
        self.items = {}

    def add_item(self, item):
        if item.goods.id in self.items:
            self.items[item.goods.id].amount += item.amount
        else:
            self.items[item.goods.id] = item
            self.num += 1

    @property
    def total(self):
        val = 0
        for item in self.items.values():
            val += item.total
        return val


def index(request):
    goods_list = Goods.objects.all()
    return render(request, 'goods.html', {'goods_list': goods_list})


def add_to_cart(request, id):
    goods = Goods.objects.get(pk=id)
    cart = request.session.get('cart', ShoppingCart())
    item = CartItem(cart.num, goods)
    cart.add_item(item)
    request.session['cart'] = cart
    return redirect('/cart')


def show_cart(request):
    current_time = datetime.now().ctime()
    last_vist_time = request.COOKIES.get('last_vist_time', '第一次访问')


    cart = request.session.get('cart', None)
    cart_items = cart.items.values() if cart else []
    total = cart.total if cart else 0
    ctx = {
        'cart_items':cart_items,
        'total': total,
        'last_vist_time': last_vist_time
    }
    response = render(request, 'cart.html', ctx)
    response.set_cookie('last_vist_time', current_time)
    return response


← Django-小结 Django-日志处理 →

Powered by Hexo, Theme designs by @hpcslag.
Style-Framework Tocas-UI designs by @yamioldmel