Django项目之电商购物商城 – 新增收货地址
-
在项目中新增收货地址我们需要根据前端的设置来写
在这里我们看到新增收货地址的方法发送的是一个ajax请求 , 使用的是post方法 , 其路由为addresses/create
分析完毕后开始写视图以及路由
一. 设置视图以及路由
因为新增地址依旧是用户的权限 , 所以我们在users该应用下创建
1. 视图
# 保存收货地址
class SaveAddressView(View):def post(self , request):json_str = request.body.decode()json_dict = json.loads(json_str)receiver = json_dict.get('receiver')province_id = json_dict.get('province_id')city_id = json_dict.get('city_id')district_id = json_dict.get('district_id')place = json_dict.get('place')mobile = json_dict.get('mobile')tel = json_dict.get('tel')email = json_dict.get('email')if not all([receiver,province_id,city_id,district_id,place,mobile]):return HttpResponseForbidden("缺少必要数据")if not re.match(r'^1[3-9]\d{9}$' , mobile):return HttpResponseForbidden("号码不正确")if tel:if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):return HttpResponseForbidden('固定电话输入有误')if email:if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):return HttpResponseForbidden('邮箱输入有误')# 将数据保存到数据库中address = Address.objects.create(user=request.user,receiver=receiver,province_id=province_id,city_id=city_id,district_id=district_id,place=place,mobile=mobile,tel=tel,email=email,)address_dict = {'id': address.id,'receiver': address.receiver,'province': address.province.area_name,'city': address.city.area_name,'district': address.district.area_name,'place': address.place,'mobile': address.mobile,'tel': address.tel,'email': address.email,}return JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})
在这里从前端获取数据以及对数据的校验都比较简单我就不重复赘述了 , 唯一要注意的是所写的字段以及命名要和前端设置的一致
2.路由
# 新增收货地址path('addresses/create/' , views.SaveAddressView.as_view())
二. 修改前端将数据传入浏览器
在这里通过vue框架传入之前写入的列表数据
<script type="text/javascript">let addresses = {{ addresses|safe }};let default_address_id = {{ default_address_id|default:0 }};</script>
通过循环获取数据
<div class="site_top_con"><a @click="show_add_site">新增收货地址</a><span>你已创建了<b>{{ count }}</b>个收货地址,最多可创建<b>20</b>个</span></div><div class="site_con" v-for="(address , index) in addresses" key="address.id"><div class="site_title"><h3>[[ address.receiver ]] [[address.province]]</h3><a @click="show_edit_title(index)" class="edit_icon"></a><em v-if="address.id===default_address_id">默认地址</em><span class="del_site">×</span></div><ul class="site_list"><li><span>收货人:</span><b>[[address.receiver]]</b></li><li><span>所在地区:</span><b>[[address.province]] [[address.city]] [[address.district]]</b></li><li><span>地址:</span><b>[[address.place]]</b></li><li><span>手机:</span><b>[[address.mobile]]</b></li><li><span>固定电话:</span><b>[[address.tel]]</b></li><li><span>电子邮箱:</span><b>[[address.email]]</b></li></ul>
新增收货地址的操作就到这里了 , 后面还需要设置默认收货地址 , 以及修改地址