Django 商城地址管理

视图界面views():

# 地址列表页
def address(request):
    # 查收此用户对应的所有地址显示到页面上
    buyer_id = request.COOKIES.get('user_id') #获取登录页面的ID
    addr_lst = Address.objects.filter(buyer_id=buyer_id) #显示对应ID的所有收货地址
    # print(addr_lst)
    return render(request, 'buyer/address.html', {'addr_lst': addr_lst}) #使用标签循环套取 (addr_lst)使用


# 添加地址
def add_address(request):
    if request.method == 'POST': #如果提交方式是POST
        buyer_name = request.POST.get('buyer') #提交的数据
        buyer_phone = request.POST.get('buyer_phone')
        buyer_address = request.POST.get('buyer_address')
        addr = Address() #建立与地址数据的链接
        addr.address = buyer_address    # 数据对应
        addr.phone = buyer_phone
        addr.recver = buyer_name
        user_id = request.COOKIES.get('user_id')
        addr.buyer = Buyer.objects.get(id=int(user_id))#   addr.buyer_id=  自动补齐 _id 看modles
        addr.save()  #存入数据库
        return redirect('/buyer/address/')  #重定向到地址页面
    return render(request, 'buyer/addAddress.html')


# 修改地址
def change_address(request):
    if request.method == 'GET': # 删除和修改html提交方式是标签 用的是GET 方式
        address_id = request.GET.get('id') 
        address_obj = Address.objects.get(id=address_id)
        return render(request, 'buyer/changeAddress.html', {'address_obj': address_obj})
    else:        # POST提交方式
        """保存修改的内容"""
        buyer_name = request.POST.get('buyer')  #获取页面提交的内容
        buyer_phone = request.POST.get('buyer_phone')
        buyer_address = request.POST.get('buyer_address')
        address_id = request.POST.get('id')  #之前页面显示的数据是用
标签ID获取的, addr = Address.objects.get(id=address_id) #获取数据库这条ID信息并修改数据库原有ID值 addr.address = buyer_address addr.phone = buyer_phone addr.recver = buyer_name addr.save()#保存 return redirect('/buyer/address/') #重定向到地址页面

地址html界面

  
                {% for address in addr_lst %}
                #循环套取数据库对象(行)
                    
                {% endfor %}
            
收货人 电话 地址 操作
{{ address.recver }} {{ address.phone }} {{ address.address }} 修改 #get 删除 #get

地址添加HTML

    #提交给 (add_address)方法  
                {% csrf_token %}
                

修改地址页面HTML

 
#提交给 (change_address)方法 {% csrf_token %}

删除地址views.py()

# 删除地址
def del_address(request, address_id):
    address_obj = Address.objects.get(id=int(address_id),buyer_id=int(request.COOKIES.get('user_id')))
    #删除对应的ADDress 里面的  ID
    address_obj.delete()

    return redirect('/buyer/address/')

删除页HTML 在地址页面添加 (上面地址页面已经写好了)
在这里插入图片描述

你可能感兴趣的:(Django 商城地址管理)