Yang
Yang

Reputation: 172

How to modify Unique and ForeignKey for Django ModelForm

I have the following code:

By default User model set username as Unique and Foreign Key, how to set email as unique and foreign key instead?

class UserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']
        widgets = {
            'username': forms.TextInput(),
            'email': forms.EmailInput(),
        }

Best Regards,

Upvotes: 0

Views: 33

Answers (2)

Yang
Yang

Reputation: 172

I totally misunderstand the concept of Database, here is the official documentation of Django ForeignKey.

  1. Current workaround, first detect whether a user is exist in existing database, return error if duplicate
  2. Set ForeignKey attribute from another model who wish to connect to User (3. Set Unique and ForeignKey in models.py not forms.py)

Upvotes: 0

Krystian Kazimierczak
Krystian Kazimierczak

Reputation: 582

I am not sure if this is the case. You can use django-allauth and in the settings.py set

ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_AUTHENTICATION_METHOD = True

https://django-allauth.readthedocs.io/en/latest/configuration.html

Upvotes: 1

Related Questions