Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Django格式的备用外键_Django_Forms_Django Forms - Fatal编程技术网

使用Django格式的备用外键

使用Django格式的备用外键,django,forms,django-forms,Django,Forms,Django Forms,我有两种型号: 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(

我有两种型号:

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”是一个自定义字符域,它将短uuid(如“mfAiC”)存储为表单中的索引。URL看起来像/view/uuid/。我想在所有URL/HTML中隐藏真实id

以及模型账户2的表格:

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>

---------
帐户1名称
我需要的是在表单中使用uuid而不是id,比如:

<select name="account_1" id="id_account_1">
    <option value="" selected="selected">---------</option>
    <option value="mfAiC">account 1 name</option>
</select>

---------
帐户1名称
我知道我可以手工做。我可以禁用account_1,创建一个表单字段,比如uuid,然后动态地为它设置选项。然后在表单验证或视图中验证表单数据


但是还有其他解决方案吗?

由于该字段是唯一的,您有理由不将其用作主键吗?根据,使用自定义主键将导致潜在问题。但你是对的,对我来说,这可能是一个好的、简单的解决办法。
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)]