我有两种模式:
class Account1(models.Model):
uuid = models.CharField(max_length=22, unique=True)
user = models.ForeignKey(User)
class Account2(models.Model):
uuid = models.CharField(max_length=22, unique=True)
account_1 = models.ForeignKey(Account1)
“uuid”是一个自定义的CharField,它将short uuid(如“mfAiC”)存储为表单中的索引。该URL看起来像/ view / uuid /。我想隐藏所有网址/ HTML中的真实ID。
模型Account2的表格:
class Account2Form(forms.ModelForm):
class Meta:
model = Account2
fields = (
'account_1',
)
def __init__(self, user, *args, **kwargs):
super(Account2Form, self).__init__(*args, **kwargs)
self.fields['account_1'].queryset = Account1.objects.filter(user=user)
呈现的HTML将是:
<select name="account_1" id="id_account_1">
<option value="" selected="selected">---------</option>
<option value="1">account 1 name</option>
</select>
我需要的是在表单中使用uuid而不是id,如:
<select name="account_1" id="id_account_1">
<option value="" selected="selected">---------</option>
<option value="mfAiC">account 1 name</option>
</select>
我知道我可以手动完成。我可以禁用account_1,创建一个表单字段,例如uuid,然后为其动态设置选项。然后在表单验证或视图中验证表单数据。
但还有其他解决方案吗?
答案 0 :(得分:0)
class Account2Form(forms.ModelForm):
account_1 = forms.ChoiceField(label='Account 1', choices=(1,1))
class Meta:
model = Account2
fields = (
'account_1',
)
def __init__(self, user, *args, **kwargs):
super(Account2Form, self).__init__(*args, **kwargs)
self.fields['account_1'].choices = [(acc1.uuid, acc1.account_name) for acc1 in Account1.objects.filter(user=user)]