user/models.py中
class AddressManage(models.Manager): '''地址模型管理类''' def get_default_addr(self, user): '''获取默认收货地址''' try: address = self.get(user=user, is_default=True) except self.model.DoesNotExist: # 不存在默认收货地址 address = None return address class Address(BaseModel): '''地址模型类''' user = models.ForeignKey('User', verbose_name='所属账户', on_delete=models.CASCADE,) receiver = models.CharField(max_length=20, verbose_name='收件人') addr = models.CharField(max_length=256, verbose_name='收件地址') zip_code = models.CharField(max_length=6, null=True, verbose_name='邮政编码') phone = models.CharField(max_length=11, verbose_name='联系电话') is_default = models.BooleanField(default=False, verbose_name='是否默认') # 自定义一个模型管理器对象 objects = AddressManage() class Meta: db_table = 'df_address' verbose_name = '地址' verbose_name_plural = verbose_name
视图函数views.py中直接调用方法
# 用户地址 # /user/address from user.models import Address class AddressView(LoginRequiredMinxin, View): def get(self, request): '''显示用户信息页面''' # 获取地址信息 user = request.user address = Address.objects.get_default_addr(user) print(address) return render(request, 'user_center_site.html', {'page':'address', 'address':address}) def post(self, request): '''添加地址''' # 接收数据 receiver = request.POST.get('receiver') zip_code = request.POST.get('zip_code') addr = request.POST.get('addr') phone = request.POST.get('phone') # 校验数据 if not all([receiver, addr, 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':'手机格式不正确'}) # 业务处理:地址添加 # 如果用户已存在默认收货地址,添加的地址不作为默认收货地址,否则作为默认收货地址 # 获取登录用户对应User对象 user = request.user address = Address.objects.get_default_addr(user) if address: is_default = False else: is_default = True # 添加地址 Address.objects.create(user=user, receiver=receiver, zip_code=zip_code, addr=addr, phone=phone, is_default=is_default) # 返回应答 刷新页面 return redirect(reverse('user:address'))