2

I have two models:

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)

The "uuid" is a custom CharField storing short uuid (like "mfAiC") as index in the form. The URL would look like /view/uuid/. I'd like to hide real id in all URL/HTML.

And the form for model 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)

The HTML rendered would be:

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

What I need is to use uuid instead of id in the form, something like:

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

I know I could do it manually. I can disable account_1, create a form field such as uuid and then dynamically set choices for it. Then verify form data in form validation or view.

But is there any other solution?

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
devfeng
  • 281
  • 4
  • 11
  • 1
    Since that field is unique, Do you have a reason not to use it as primary key? – AJJ May 09 '12 at 11:16
  • According to [this answer](http://stackoverflow.com/a/3944247/765615), using custom primary key will cause potential problems. But yes you are right, it may be a good and easy solution in my case. – devfeng May 09 '12 at 16:47
  • this the pest question , yes i don't wan't using forign key in complix and huge tables for avoid circumistance problem – Youssri Abo Elseod Jul 24 '22 at 06:56

1 Answers1

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)]
super9
  • 29,181
  • 39
  • 119
  • 172