31 ModelForm常用功能--扩充
ModelForm自定义字段的显示效果
class ChargeModelForm(BootStrapModelForm, forms.ModelForm):
# 静态变量
# charge_type = forms.ChoiceField(
# label='类型',
# choices=[(1, '充值'), (2, '扣款')], # 只适合固定的数据,不适合去数据表中获取数据(注意:此方式前端提交的数据为str类型)
# )
charge_type = forms.TypedChoiceField(
label='类型',
choices=[(1, '充值'), (2, '扣款')],
coerce=int # 获取值之后会自动将数据转换成int类型
)
class Meta:
model = models.TransactionRecord
fields = ['charge_type', 'amount']
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# # 每次实例化就重新调用该方法(注意:此方式前端提交的数据为int类型)
# self.fields['charge_type'].choices = [(1, '扣款'), (2, '充值')]
def customer_charge(request, pk):
queryset = models.TransactionRecord.objects.filter(customer_id=pk, customer__active=1).order_by('-id')
pager = Pagination(request, queryset)
form = ChargeModelForm()
return render(request, 'customer_charge.html', {'pager': pager, 'form': form})
class TransactionRecord(models.Model):
"""交易记录"""
charge_type_class_mapping = {
1: 'success',
2: 'danger',
3: 'default',
4: 'info',
5: 'primary',
}
charge_type_choices = ((1, '充值'), (2, '扣款'), (3, '创建订单'), (4, '删除订单'), (5, '撤单'))
charge_type = models.SmallIntegerField(verbose_name='类型', choices=charge_type_choices)
customer = models.ForeignKey(verbose_name='客户', to='Customer', on_delete=models.CASCADE)
amount = models.DecimalField(verbose_name='金额', default=0, max_digits=10, decimal_places=2)
creator = models.ForeignKey(verbose_name='管理员', to='Administrator', on_delete=models.CASCADE, null=True, blank=True)
order_oid = models.CharField(verbose_name='订单号', max_length=64, null=True, blank=True, db_index=True)
create_datetime = models.DateTimeField(verbose_name='交易时间', auto_now_add=True)
memo = models.TextField(verbose_name='备注', null=True, blank=True)
ModelForm返回数据的问题处理
问题1:返回页面数据是对象的解决方式
在models 中,配置相应表的 __str__ 方法的返回值
问题2:返回的数据,个别的字段需要过滤条件,怎么解决?
方式1:在需要过滤条件models表中的字段中,配置如下
level = models.ForeignKey(verbose_name='级别', to='Level', on_delete=models.CASCADE, limit_choices_to={"active": 1})
方式2:在ModelForm中,写 init 方法
class CustomerModelForm(BootStrapModelForm, forms.ModelForm):
class Meta:
model = models.Customer
fields = ['username', 'mobile', 'password', 'level']
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
# data = request.GET.get('xxx') # 该获取的参数是扩展,可以在实例化对象时,传入request参数
self.fields['level'].queryset = models.Level.objects.filter(active=1)
def customer_add(request):
form = CustomerModelForm() # 有需要动态获取值的,在这里传入request参数
return render(request, 'form2.html', {'form': form})
问题3:返回choices字段,只取个别的值
class ChargeModelForm(BootStrapModelForm, forms.ModelForm):
# 方式1:
creator = forms.ChoiceField(
label='管理员',
choices=models.Administrator.objects.filter(ig__gt=1).values_list('id', 'username')
)
class Meta:
model = models.TransactionRecord
fields = ['creator']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 每次实例化就重新调用该方法(注意:此方式前端提交的数据为int类型)
# 方式2:
self.fields['charge_type'].choices = models.Administrator.objects.filter(ig__gt=1).values_list('id', 'username')