Extending User fields in UserCreationForm - django

I am trying to add some custom fields to a user, and extend the UserCreationForm so that I can add these fields when the user is created. I am following the docs but when I try to load the page to create a user I get an error: Unknown field(s) (username) specified for Customer.
The docs that I am following: Custom User and Auth Forms
models.py
class User(AbstractUser):
is_restaurant = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
class Customer(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
address = models.CharField(max_length=200)
def __str__(self):
return self.user.get_full_name()
forms.py
class CustomerSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = Customer
fields = UserCreationForm.Meta.fields + ('address',)
I understand that username is not part of the Customer class, but the docs appear to be doing the same thing...

The doc says:
If your custom user model is a simple subclass of AbstractUser, then
you can extend these forms in this manner...
In other words this will work only in case you want to add to the form is_restaurant or is_customer fields:
class CustomerSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('is_restaurant',)
But in your case Customer is not subclass of AbstractUser, since this method is not working for you. As a workaround you can try to work with two separate forms in the same time as suggested in this answer.

Related

How to access foreignkey/ OneToOneField table's data from a ModelForm?

I have a model called Profile that is related to the User Model. I would like to make a ModelForm for the model Profile. I would like that form to be able to access user's fields.
class Profile(models.Model):
user=models.OneToOneField(settings.AUTH_USER_MODEL,related_name='profile',on_delete=models.CASCADE)
address = models.CharField(max_length=250)
contact_number = models.IntegerField(max_length=20)
def __str__(self):
return self.user.first_name
class ProfileForm(forms.ModelForm):
class Meta:
model=Profile
fields=['first_name','address','contact_number']
The error shown is
django.core.exceptions.FieldError: Unknown field(s) (first_name) specified for Profile
Thank you.

How to limit fields in Form Django 2.2?

I got problem on limiting field shown in forms.ModelForm.
I Use Django 2.2
Currently I have
models.py
class MyModel(models.Model) :
user = models.ForeignKey(User, on_delete=models.CASCADE)
justchar = models.CharField(max_length=20, blank=True, null=True)
admins.py
class MyModelAdmin(admin.ModelAdmin) :
form=MyModelForm
admin.site.register(MyModel,MyModelAdmin)
form.py
class MyModelForm(forms.ModelForm) :
class Meta:
fields = ['user']
But the form still shows all fields.
I also tried with 'exclude', but got same results
You don't need a form for this. In fact, as the admin docs explicitly state, the fields attribute on a modelform is ignored in the admin.
Instead, just set fields directly on the admin class:
class MyModelAdmin(admin.ModelAdmin) :
fields = ['user']
admin.site.register(MyModel,MyModelAdmin)

create a user in Django 2.1 that is associated with an existing model

In my models.py file I have the following code ->
from django.db import models
class Blogger(models.Model):
username = models.CharField(max_length=20)
email = models.EmailField()
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
password = models.CharField(max_length=30, default='')
I want to associate the Blogger model with a User and create the User upon form submission. Here is the forms.py file ->
from django import forms
from blog.models import Blogger
class BloggerForm(models.ModelForm):
class Meta:
model = Blogger
fields = ['username', 'email', 'first_name', 'last_name', 'password']
And here is the views.py ->
class BlogView(FormView):
template_name = 'blogform.html'
form_class = BloggerForm
success_url = 'blog/'
How do I create a new user on the submission of this form ?
All fields in blogger already exists in User model, actually you don't need this Blogger model at all, just use the User model directly.
There's a couple ways you can do this but basically the general 2 answers are:
Toss/copy Django's user model and make your own (hard)
Extend the user model by making a new model, and relating it to the user model (easy)
I usually choose option #2 because then you don't have to reconfig the auth system. This is a good tutorial on how to do it: simpleisbetterthancomplex

how to attach multiple ModelAdmins to UserAdmin in Django?

I have a search model which has a ForeignKey relation to User
class Searches(models.Model):
user = models.ForeignKey(User)
......
I have a UserProfile model which has a OnetoOne Relationship to User
class UserProfile(models.Model):
user = models.OneToOneField(User)
photo = models.ImageField(upload_to='profile_images', blank=True)
ispublic=models.NullBooleanField()
I have attached UserProfile in admin.py as follows:
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
class UserProfileAdmin(UserAdmin):
inlines=(UserProfileInline, )
list_filter = UserAdmin.list_filter + ('email',)
list_display=('username','email','first_name','last_name','isPublic')
admin.site.unregister(get_user_model())
admin.site.register(get_user_model(), UserProfileAdmin)
Now I do not see a separate UserProfile but is integrated into User, which is what I want.
I also want to have Search model to show up in User admin. But also seperately.
how can I register two (or more) Admins to User model?
Try just putting another Inline inside the UserProfileAdmin, that will then place the UserProfileInline and SearchesInline in the UserProfileAdmin, then put admin.site.register(Searches) in admin.py. Unless I misunderstand the question.

Django: CustomUser model does not have the attributes of built-in User

I have a problem with the CustomUser Model. Here is the model:
class CustomUser(models.Model):
department = models.ManyToManyField(Department)
game = models.ManyToManyField(Game)
user = models.OneToOneField(User)
In my user registration form, I want to have fields of User plus the Game and Department fields. Here's my form as of now:
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(max_length = '200')
last_name = forms.CharField(max_length = '200')
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email')
I used User as my Model, so clearly it does not have the Game and Department fields as of now. At the same time, if I use CustomUser as a model in my form, I do have all the fields I need, but when I click the register button, an error: "CustomUser does not have a set_password attribute" appears.
Also, in Setting I have this:
CUSTOM_USER_MODEL = 'logins.CustomUser'
So how can I make the CustomUser Model have the attributes of User and have those fields appear in my form?
Thanks in advance!
When creating your own custom user model, it's usually best to subclass the AbstractBaseUser which includes those default fields and will generally make the process easier on you. OneToOne relationship to the default User model is more about expnding the built-in User model, which doesn't sound like what you're looking for. Read more about it here
As Daniel mentioned in the comments, this means you're going to have to explicitly include the username field (and you obviously have the freedom to define it as you'd like, it just has to be unique). In the example below I set up email to be the username
from django.contrib.auth.models import AbstractBaseUser
class CustomUser(AbstractBaseUser):
department = models.ManyToManyField(Department)
game = models.ManyToManyField(Game)
# user = models.OneToOneField(User)
email = models.EmailField(max_length=255, unique=True, db_index=True)
USERNAME_FIELD = 'email'
Now you need to include the password field in your form, and please look at the example given in the documentation, they do a better job explaining than I do.