11用戶中心--地址頁

user/urls.pyhtml

from django.urls import path
from .import views

urlpatterns = [
    path('register/',views.RegisterView.as_view()), # 註冊
    path('active/<token>',views.ActiveView.as_view()), # 用戶激活
    path('login/',views.LoginView.as_view()), # 登陸
    path('login_out/',views.LoginOut.as_view()), # 退出登陸
    path('',views.UserInfoView.as_view()), # 用戶中心-我的信息
    path('order/',views.UserOrderView.as_view()), # 用戶中心-所有訂單
    path('address/',views.UserAddress.as_view()), # 用戶中心-收貨地址

]

user/views.pydjango

class UserAddress(View):
    '''用戶中心-地址頁'''
    def get(self, request):

        if 'user' not in request.session:
            return redirect('/user/login/')

        #  獲取用戶默認收貨地址
        user = jsonpickle.loads(request.session.get('user',''))

        try:
            address = Address.objects.get(user=user,is_default=True)
        except Address.DoesNotExist:
            # 不存在默認收貨地址
            address = None

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

    def post(self,request):
        # 接受數據
        receiver = request.POST.get('receiver', '')
        addr = request.POST.get('addr', '')
        zip_code = request.POST.get('zip_code', '')
        phone = request.POST.get('phone', '')

        # 校驗數據
        if not all([receiver,addr,zip_code,phone]):
            return render(request,'user_center_site.html',{'errmsg':'信息不完整'})

        # 驗證手機號
        if not re.match(r'^1[3|4|5|7|8][0-9]{9}$',phone):
            return render(request, 'user_center_site.html', {'errmsg': '手機格式錯誤'})

        # 獲取session
        user = jsonpickle.loads(request.session.get('user'))

        # 添加地址
        # 若是用戶已存在默認收貨地址,添加的地址不做爲默認收貨地址,不然做爲默認收貨地址
        try:
            address = Address.objects.get(user=user,is_default=True)
        except Address.DoesNotExist:
            # 不存在默認收貨地址
            address = None

        # 若是存在默認收貨地址
        if address:
            is_default = False
        else:
            is_default = True

        # 添加地址
        Address.objects.create(user=user,receiver=receiver,addr=addr,zip_code=zip_code,phone=phone,is_default=is_default)

        return redirect('/user/address/')

user_center_site.htmljson

<div class="site_con">
    <dl>
        <dt>當前地址:</dt>
        {% if address %}
        <dd>{{ address.addr }} ({{ address.receiver }})收 {{ address.phone }}</dd>
        {% else %}
        <dd>無默認地址</dd>
        {% endif %}
    </dl>                   
</div>
相關文章
相關標籤/搜索