Lanms Blog

Django-表单提交,equest.method-cookie-session
Publish: 2019/3/21   

表单提交, request.method cookie session

表单提交的令牌

{-%- csrf_token-%-}

ModelForm, 也可以添加额外的验证, clean_开头的方法写验证的条件

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可以不填

  def clean_carno(self):  # 验证数据, clean_开头,
                            # 加对应的字段名字 自动执行下面的验证规则

      _carno = self.cleaned_data['carno']
      if _carno in condition:
          #写验证条件, 验证通过
          return self._carno
      else:
          # 验证失败, 没通过
          raise forms.ValidationError('错误信息')

  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})



#### request 请求 method / POST /  GET

- `request.method == 'GET' / 'POST'`

- request里面有GET和POST属性

  - `request.POST`为表单提交的内容 

- 返回的内容, 返回JSON 字符串, (代码示例为==car_完整版==)

  ```python
  from django.http import HttpResponse, JsonResponse

  HttpResponse(json.dumps(your_data),content_type='application/json; charset=utf-8')

  # 也可以用 Jsonresponse, 但是要先自定义编码器, encoder

  return JsonResponse(your_data, encoder=YourEncoder, safe=False)

  class YourEncoder(DjangoJSONEncoder):  # 继承自DjangoJSONEncoder, 
                                         # 或者 JsonEncoder
      def defaulf(self, o):   #重写default方法
          a = o.model.__dict__
          del a['_satae']
          return a

cookie和session

Cookie - > 浏览器 session –> 服务器

cookie 用户跟踪, 存放有sessionid

示例, 对访问时间信息的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

Session应用

示例代码

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-web页面Django的增删改查-主要是代码示例 Django-小结 →

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