day54-Django项目-天天生鲜

一、提交订单模块

1.在urls.py配置文件中定义路由

from django.conf.urls import url, include

from order import views

urlpatterns = [
    # 结算订单页面
    url(r'^place_order/', views.place_order, name='place_order'),
    # 下单
    url(r'^make_order/', views.make_order, name='make_order'),
]

2.生成随机订单号

import random
import time


# 生成订单交易号
def get_order_sn():
    s = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
    order_sn = ''
    for i in range(3):
        order_sn += random.choice(s)
    order_sn += str(time.time())
    return order_sn

3.提交订单功能

from django.http import JsonResponse
from django.shortcuts import render

from carts.models import ShoppingCart
from order.models import OrderInfo, OrderGoods
from user.models import UserAddress
from utils.function import get_order_sn


def place_order(request):
    if request.method == 'GET':
        user_id = request.session.get('user_id')
        shop_carts = ShoppingCart.objects.filter(user_id=user_id, is_select=1)
        user_address = UserAddress.objects.filter(user_id=user_id)
        # 给购物车中的对象绑定一个新增的属性,其值为小计价格
        all_total = 0
        for carts in shop_carts:
            carts.price = carts.nums * carts.goods.shop_price
            all_total += carts.price
        # 结算商品个数,总价
        carts_count = len(shop_carts)

        return render(request, 'place_order.html', {'shop_carts': shop_carts, 'carts_count': carts_count,
                                                    'all_total': all_total, 'user_address': user_address})


def make_order(request):
    if request.method == 'POST':
        user_id = request.session.get('user_id')
        # 取购物车中勾选的商品
        shop_carts = ShoppingCart.objects.filter(user_id=user_id, is_select=1)
        # 计算下单的总价
        order_mount = 0
        for carts in shop_carts:
            order_mount += carts.nums * carts.goods.shop_price
        # 生成订单交易号
        order_sn = get_order_sn()
        # 1.创建订单
        address_id = int(request.POST.get('address_id'))
        user_address = UserAddress.objects.filter(pk=address_id).first()
        order = OrderInfo.objects.create(user_id=user_id, order_sn=order_sn, order_mount=order_mount,
                                         address=user_address.address, signer_name=user_address.signer_name,
                                         signer_mobile=user_address.signer_mobile)
        # 2.创建订单详情
        for carts in shop_carts:
            OrderGoods.objects.create(order=order, goods=carts.goods, goods_nums=carts.nums)
        # 3.删除购物车中的商品
        shop_carts.delete()
        request.session.pop('goods')

        return JsonResponse({'code': 200, 'msg': '请求成功'})

4.前端页面代码

{% extends 'base_main.html' %}

{% block title %}
    天天生鲜-提交订单
{% endblock %}

{% block search %}
{% endblock %}

{% block content %}
    
    

确认收货地址

寄送到:
{% for user_address in user.useraddress_set.all %}
{{ user_address.address }} ({{ user_address.signer_name }} 收) {{ user_address.signer_mobile }}
{% endfor %}
编辑收货地址

支付方式

商品列表

  • 商品名称
  • 商品单位
  • 商品价格
  • 数量
  • 小计
{% for carts in shop_carts %}
  • {{ forloop.counter }}
  • {{ carts.goods.name }}
  • 500g
  • {{ carts.goods.shop_price }}
  • {{ carts.nums }}
  • {{ carts.price }}
{% endfor %}

总金额结算

{{ carts_count }}件商品,总金额{{ all_total }}
运费:10元
实付款:{{ all_total | add:10 }}元
{% endblock %} {% block footer %} {{ block.super }} {% endblock %} {% block js2 %} {% csrf_token %} {% endblock %}

二、个人信息模块

1.在urls.py配置文件中定义路由

from django.conf.urls import url, include

from user import views

urlpatterns = [
    # 用户中心
    url(r'^user_center_info/', views.user_center_info, name='user_center_info'),
]

2.个人信息

from django.shortcuts import render


def user_center_info(request):
    if request.method == 'GET':
        return render(request, 'user_center_info.html')

3.前端页面代码

{% extends 'base_main.html' %}

{% block title %}
    天天生鲜-用户中心
{% endblock %}

{% block search %}
    
{% endblock %}

{% block content %}
    

基本信息

最近浏览

{% endblock %}

三、订单详情模块

1.在urls.py配置文件中定义路由

from django.conf.urls import url, include

from user import views

urlpatterns = [
    # 订单详情
    url(r'^user_center_order/', views.user_center_order, name='user_center_order'),
]

2.订单详情

from django.core.paginator import Paginator
from django.shortcuts import render

from order.models import OrderInfo


def user_center_order(request):
    if request.method == 'GET':
        user_id = request.session.get('user_id')
        page_num = request.GET.get('page', 1)
        order_info = OrderInfo.objects.filter(user_id=user_id)
        paginator = Paginator(order_info, 5)
        page = paginator.page(page_num)
        return render(request, 'user_center_order.html', {'page': page})

3.前端页面代码

{% extends 'base_main.html' %}

{% block title %}
    天天生鲜-用户中心
{% endblock %}

{% block search %}
    
{% endblock %}

{% block content %}

    

全部订单

{% for order in page %}
  • {{ order.add_time }}
  • 订单号:{{ order.order_sn }}
  • {{ order.pay_status }}
{% for order_goods in order.goods.all %}
  • {{ order_goods.goods.name }}{{ order_goods.goods.shop_price }}元/500g
  • {{ order_goods.goods_nums }}
  • 11.80元
{% endfor %}
{{ order.order_mount }}元 待付款 去付款
{% endfor %}
{% endblock %}

四、收货地址模块

1.在urls.py配置文件中定义路由

from django.conf.urls import url, include

from user import views

urlpatterns = [
    # 用户收货地址
    url(r'^user_center_site/', views.user_center_site, name='user_center_site'),
]

2.定义收货地址验证form表单

from django import forms

from user.models import User


class UserRegisterForm(forms.Form):
    user_name = forms.CharField(max_length=20, min_length=5, required=True,
                                error_messages={
                                    'required': '用户名必填',
                                    'max_length': '用户名不能超过20位字符',
                                    'min_length': '用户名不能少于5位字符',
                                })
    pwd = forms.CharField(max_length=20, min_length=8, required=True,
                          error_messages={
                              'required': '密码必填',
                              'max_length': '密码不能超过20位字符',
                              'min_length': '密码不能少于8位字符'
                          })
    cpwd = forms.CharField(max_length=20, min_length=8, required=True,
                          error_messages={
                              'required': '确认密码必填',
                              'max_length': '密码不能超过20位字符',
                              'min_length': '密码不能少于8位字符'
                          })
    email = forms.CharField(required=True,
                            error_messages={
                                'required': '邮箱必填'
                            })

    # 验证时,会自动调用
    def clean(self):
        # 校验用户名是否已存在于数据库
        user =User.objects.filter(username=self.cleaned_data.get('user_name')).first()
        if user:
            # 用户已存在于数据库,抛出异常
            raise forms.ValidationError({'user_name': '该用户已存在'})
        # 校验密码是否相等
        pwd = self.cleaned_data.get('pwd')
        cpwd = self.cleaned_data.get('cpwd')
        if pwd != cpwd:
            raise forms.ValidationError({'pwd': '两次密码不一致'})
        return self.cleaned_data


class UserLoginForm(forms.Form):
    username = forms.CharField(required=True,
                               error_messages={
                                   'required': '用户名必填',
                               })
    pwd = forms.CharField(required=True,
                          error_messages={
                              'required': '密码必填',
                          })

    # def clean(self):
        # 验证登录的账号是否已经被注册过,注册过才能登录
        # user = User.objects.filter(username=self.cleaned_data.get('username')).first()
    #     if not user:
    #         raise forms.ValidationError({'username': '该账号没有注册'})
    #
        # return self.cleaned_data


class UserAddressForm(forms.Form):
    signer_name = forms.CharField(required=True,
                                  error_messages={
                                      'required': '收件人必填'
                                  })
    address = forms.CharField(required=True,
                              error_messages={
                                  'required': '必填'
                              })
    postcode = forms.CharField(required=True,
                               error_messages={
                                   'required': '邮编必填'
                               })
    mobile = forms.CharField(required=True,
                             error_messages={
                                 'required': '手机必填'
                             })

3.收货地址

from django.shortcuts import render
from django.urls import reverse

from user.forms import UserAddressForm
from user.models import UserAddress


def user_center_site(request):
    if request.method == 'GET':
        user_id = request.session.get('user_id')
        user_address = UserAddress.objects.filter(user_id=user_id)

        return render(request, 'user_center_site.html', {'user_address': user_address})

    if request.method == 'POST':
        # 使用表单做校验
        form = UserAddressForm(request.POST)
        if form.is_valid():
            user_id = request.session.get('user_id')
            address = form.cleaned_data['address']
            signer_name = form.cleaned_data['signer_name']
            postcode = form.cleaned_data['postcode']
            mobile = form.cleaned_data['mobile']
            UserAddress.objects.create(user_id=user_id, address=address, signer_name=signer_name,
                                       signer_postcode=postcode, signer_mobile=mobile)

            return HttpResponseRedirect(reverse('user:user_center_site'))
        else:
            errors = form.errors

            return render(request, 'user_center_site.html', {'errors': errors})

4.前端页面代码

{% extends 'base_main.html' %}

{% block title %}
    天天生鲜-用户中心
{% endblock %}

{% block search %}
    
{% endblock %}

{% block content %}
    

收货地址

当前地址:
{% for address in user_address %} {% if address %}
{{ address.address }} ({{ address.signer_name }} 收) {{ address.signer_mobile }}
{% else %}
{% endif %} {% endfor %}

编辑地址

{% csrf_token %}
{{ errors.signer_name }}
{{ errors.address }}
{{ errors.postcode }}
{{ errors.mobile }}
{% endblock %}

你可能感兴趣的:(day54-Django项目-天天生鲜)