有我的模特:
class MoneyTransfer(models.Model):
sender = models.ForeignKey(BankAccount, related_name='outcome_transfers')
receiver = models.ForeignKey(BankAccount, related_name='income_transfers')
when = models.DateTimeField()
total = models.FloatField()
comment = models.CharField(max_length=255)
objects = TransferQuerySet.as_manager()
形式:
SendTransferForm = select2_modelform(MoneyTransfer)
我有两种形式的用法:
1. fields = 'receiver', 'comment', 'total'
2. fields = 'sender', 'receiver', 'comment', 'total'
如何在代码中实现它?
答案 0 :(得分:1)
您可以创建两个表单类
class FirstForm(ModelForm):
class META:
model = models.MoneyTransfer
fields = ['receiver', 'comment', 'total']
然后:
class SecondForm(ModelForm):
class META:
model = models.MoneyTransfer
fields = ['sender', 'receiver', 'comment', 'total']
答案 1 :(得分:0)
我决定不使用模型表单并使用必要的小部件创建简单表单:
class SendTransferForm(forms.Form):
sender = forms.ModelChoiceField(queryset=BankAccount.objects.all(), widget=Select2(), label="Счёт отправителя")
receiver = forms.ModelChoiceField(queryset=BankAccount.objects.all(), widget=Select2(), label="Счёт получателя")
total = forms.CharField(widget=forms.TextInput(attrs={'class': 'select2fake'}), label="Сумма")
comment = forms.CharField(widget=forms.TextInput(attrs={'class': 'select2fake'}), label="Комментарий")