Will Joseph
Will Joseph

Reputation: 33

Trying to add custom fields to users in Django

I am fairly new to django and was it was going well until this.

i'm trying to add fields 'address' and 'phone_number' to users (create custom user basically) but i keep getting this error like this...

File "C:\Users\will5\Desktop\City\city_info\forms.py", line 5, in <module>
class UserForm(forms.ModelForm):
File "C:\Users\will5\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\forms\models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (phone_number, address) 
specified for User

this is models

...
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    phone_number = models.IntegerField(default=0)
    address = models.CharField(max_length=150)
...

this is in my forms

from django.contrib.auth.models import User
from django import forms

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

class Meta:
    model = User
    fields = ['username', 'email', 'password', 'address', 'phone_number']

I also read that in order to fix this problem i will have to restart my project by creating the custom user and migrating and i don't wanna do that.

Upvotes: 1

Views: 213

Answers (1)

Alasdair
Alasdair

Reputation: 309109

The problem is that you are still importing the built in user model

You can fix it by replacing

from django.contrib.auth.models import User

with

from django.contrib.auth import get_user_model
User = get_user_model()

This assumes that you have set AUTH_USER_MODEL = 'yourapp.User' in your settings.

As you have read in the docs, it is extremely difficult to switch to a custom user model after the project has started, there isn't an easy solution to this. If you can't restart your project, perhaps you could create a Profile model with a OneToOneField to the default User instead.

Upvotes: 1

Related Questions