Add field to django admin - python

So I'm using this custom user to replace the default login with username by email.
But I still want my user to have an username so I've done what they say in the doc. But in my admin, when I want to create or update my user I've not the field "username".
Here is my code.
models:
from django.db import models
from custom_user.models import AbstractEmailUser
class Account(AbstractEmailUser):
username = models.CharField(unique=True, max_length=50)
admin
from django.contrib import admin
from custom_user.admin import EmailUserAdmin
from authentication.models import Account
class AccountAdmin(EmailUserAdmin):
list_display = ('email', 'username')
# fields = ('email', 'username', 'password')
admin.site.register(Account, AccountAdmin)
I've try to put the fields thing but I've got the following error.
ERRORS:
: (admin.E005) Both 'fieldsets' and 'fields' are specified.
I'm using python 3.4 and django 1.8

Your EmailUserAdmin probably already defines fieldsets.
Look at the definition of EmailUserAdmin, and declare fieldsets in AccountAdmin accordingly, instead of using fields.
You'll probably want to keep the documentation on fieldsets handy.

Related

I want to create custom signup form and add extra fields in Django default user model

I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city.
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
full_name=forms.CharField(max_length=50,required=True)
phone_number=forms.CharField(widget=forms.TextInput(attrs={'type':'number'}))
address=forms.CharField(max_length=200,required=True)
city=forms.CharField(max_length=200,required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2','full_name','phone_number','address','city')
def register(self):
self.save()
I created form by using this method. First, created forms.py for extra fields then inherited it. It is working; but still some fields disappear.
Because, you are adding additional fields to the default user model. First you have to
-Create a Custom User Model by using AbstractUser
Then
-Create a Custom Form for UserCreationForm
You can search google for:
Extend-existing-user-model-in-django

How to use UserCreationForm in Django?

I have followed this tutorial to test out the User authentication and Signals in Django. I don't know what I should do with this part (found from the first post of this tutorial):
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
birthdate = forms.DateField()
discord_id = forms.CharField(max_length=100, help_text='Discord ID')
zoom_id = forms.CharField(max_length=100, help_text='Zoom ID')
text = forms.TextField(null=True, blank=True)
class Meta:
model = User
fields = ["username", "password1", "password2", "birthdate", "email", "discord_id", "zoom_id"]
With those imports I get an error NameError: name 'forms' is not defined and if I add an import from django import forms I get errors like AttributeError: module 'django.forms' has no attribute 'TextField'.
Sohuld I add all the fields from my Model into this RegisterForm -class I want to include to the registration process? What do I do to the fields that are textFields in my Model?
Instead of using forms.TextField which does not exist in Django, you need to use forms.CharField(widget=forms.Textarea).
I think you are trying to use CharField instead of TextField. Django uses CharField in its forms with default widget as TextArea.
You can find more details here
https://docs.djangoproject.com/en/3.2/ref/forms/fields/#charfield

Merging "add" form in Django Admin from 2 or more Models (connected with one-to-one relationship)

I have a Django's default UserCreationForm to add a new user via Admin app. I want to add new fields from another custom model called UserProfile. The UserProfile has a One-to-One relationship with Django's User model. The additional fields which UserProfile model has are phone number, company name etc.
Is there a way where I can merge UserProfile form with Django's default User form while creation of the new user from Admin panel?
I looked at Django's documentation here on Inline forms but seems their require foreign key relationship.
Django 2.1
Assuming you have Profile with extra field phone_number. Like this
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
phone_number = models.CharField(max_length=24)
You can follow following steps to add extra fields in UserCreationForm in Admin.
1. Create custom UserCreationForm
Inherit from UserCreationForm and Add extra fields and functionality.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from account.models import Profile
class UserWithProfileCreationForm(UserCreationForm):
phone_number = forms.CharField(max_length=32)
def save(self, commit=True):
instance = super().save(commit=True)
profile = Profile(user=instance, phone_number=self.cleaned_data['phone_number'])
profile.save()
return instance
2. Unregister (already registered) User model and register again with custom form and fields
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# unregister first
admin.site.unregister(User)
#admin.register(User)
class UserWithProfileAdmin(UserAdmin):
add_form = UserWithProfileCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
# add any custom fields here
'fields': ('username', 'password1', 'password2', 'phone_number'),
}),
)
There are two ways to do this.
First, you can create a custom User model from AbstractBase
# models.py
class MyUser(AbstractBaseUser):
profile = models.OneToOneField(UserProfile)
And then update your admin view.
#admin.py
from django.contrib.auth.admin import UserAdmin
class UserProfileInline(admin.TabularInline):
model = UserProfile
class MyUserAdmin(UserAdmin):
inlines = [
UserProfileInline,
]
admin.site.register(MyUser, MyUserAdmin)
Second, you can simply add the OneToOneField(User) in your UserProfile model, and follow the similar method to update the admin view.

Making first name, last name a required attribute rather than an optional one in Django's auth User model

I'm trying to make sure that the first name and last name field are not optional for the auth User model but I'm not sure how to change it. I can't use a sub class as I have to use the authentication system.
Two solutions I can think of are:
to put the name in the user profile but it's a little silly to have a field that I can't use correctly.
To validate in the form rather than in the model. I don't think this really fits with Django's philosophy...
For some reason I can't seem to find a way to do this online so any help is appreciated. I would have thought that this would be a popular question.
Cheers,
Durand
Simplest solution
Just create a custom UserRegisterForm which inherits the django's default UserCreationForm.
The first_name and last_name are already attributes of django's default User. If you want to make them as required fields, then recreate those fields as forms.CharField(...).
Now use your own User register form.
# Contents usersapp/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Inherit Django's default UserCreationForm
class UserRegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=50) # Required
last_name = forms.CharField(max_length=50) # Required
# All fields you re-define here will become required fields in the form
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2']
I would definitely go with validating on the form. You could even go as far as having more form validation in the admin if you felt like it.
Thanks Mbuso for the advice. Here's my full implementation for those who are interested. Before taking a look at the source, let's see what it looks like:
I've implemented a profile model, but this will work just fine without it.
from django.core.exceptions import ValidationError
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import User
from apps.profiles.models import Profile
# Define an inline admin descriptor for Profile model
# which acts a bit like a singleton
class UserProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'profile'
class MyUserChangeForm(UserChangeForm):
def clean_first_name(self):
if self.cleaned_data["first_name"].strip() == '':
raise ValidationError("First name is required.")
return self.cleaned_data["first_name"]
def clean_last_name(self):
if self.cleaned_data["last_name"].strip() == '':
raise ValidationError("Last name is required.")
return self.cleaned_data["last_name"]
# Define a new User admin
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
inlines = UserProfileInline,
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
Note: If you do implement a profile model, recommend using UserProfile as the name, since is this is what's in the documentation and seems to be the standard (this part was developed before I started working on the project). If you're using Django 1.5 or higher, skip UserProfile all together and extend the User model.
The Django way of extending the basic User model is through user profiles: see "Storing additional information about users".
If it does not fit your needs, django.contrib.auth is just a Django application, I would simply fork it. As long as you abide by the original interface, I think you will be out of trouble.
Another option is Pinax - it has OpenId support built in, you can use it with your own openid provider. OpenId native support is a battery I really miss in Django.

Django admin panel doesn't work after modify default user model

I was trying to extend user profile. I founded a few solutions, but the most recommended was to create new user class containing foreign key to original django.contrib.auth.models.User class. I did it with this so i have in models.py:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
website_url = models.URLField(verify_exists=False)
and in my admin.py
from django.contrib import admin
from someapp.models import *
from django.contrib.auth.admin import UserAdmin
# Define an inline admin descriptor for UserProfile model
class UserProfileInline(admin.TabularInline):
model = UserProfile
fk_name = 'user'
max_num = 1
# Define a new UserAdmin class
class MyUserAdmin(UserAdmin):
inlines = [UserProfileInline, ]
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
And now when I'm trying to create/edit user in admin panel i have an error:
"Unknown column 'content_userprofile.id' in 'field list'" where content is my appname.
I was trying to add line AUTH_PROFILE_MODULE = 'content.UserProfile' to my settings.py but with no effect.
How to tell panel admin to know how to correctly display fields in user form?
After some effort I found working solution:
the AUTH_PROFILE_MODULE = 'content.UserProfile' is required
please drop your database (auth_user, yourapp_userprofile tables should be enough)
finally python manage.py syncdb

Categories

Resources