Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending new user form, in the admin Django

Tags:

django

admin

I have added an extra field for the User by doing the whole process where making User Profile app and extending the User module.

It doesn't seem to error. What I cant figure out, or find anywhere is how to show this new field in the page where an admin creates a new user. So under personal information such as First name and last Name I want there to be Location field that I added to User Profile.

my User Profile:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    # This field is required.
    user = models.OneToOneField(User)

    # Other fields here
    location = models.CharField(max_length=20)

# definition of UserProfile from above
# ...

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

also I would like to know how to make the email mandatory, like password and username. Just changing the user model in the Django folder to:

 email = models.EmailField(_('e-mail address'), unique=True)

didn't work at all.

[UPDATE] So this is my admin.py hat I created. Where should i include this in the settings.py file so that it would actually use the folder with the added user module and the new form? I have this line but it doesnt seem to use the new form at all AUTH_PROFILE_MODULE = 'UserProfile.UserProfile' (i have a folder called UserProfile which contains the two snipets of code)

from django.contrib import admin
from django.contrib.auth.models import User,Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.admin.views.main import *

class MyUserCreationForm(UserCreationForm):
    """
    A form that creates a user, with no privileges, from the given username and password.
    """
    OFFICES = (
        (0, "Global"),
        (1, "Dublin"),
        (2, "Tokyo"),
        (3, "Warsaw"),
        (4, "Beijing"),
        (5, "Seoul"),
        (6, "Taipei"),
        (7, "Orem"),
        (8, "Mountain View"),
        (9, "San Luis Obispo"),
        (10, "Roseville"),
        (11, "Pune"),
        (12, "i18n")
    )
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
        help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
        error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
        help_text = _("Enter the same password as above, for verification."))
    location = forms.IntegerField(label=_("Location"), choices=TYPE_CHOICES)

    class Meta:
        model = User
        fields = ("username",)

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(_("A user with that username already exists."))

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(_("The two password fields didn't match."))
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class CustomUserAdmin(UserAdmin):
    add_form = MyUserCreationForm
    inlines = [ProfileInline,]
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2', 'location')}
        ),
    )


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Class, ClassAdmin)
like image 577
Angie Avatar asked Jul 28 '11 11:07

Angie


1 Answers

You'll need to use your own UserAdmin class and modify the add_fieldsets property to alter the fields that are displayed. See this Stack Overflow question for an example.

If you want to edit your UserProfile instance at the same time as the User, one approach is to add the UserProfile as an inline to your custom UserAdmin. Hope that helps you out.

Example of un-registering the built-in model admin for user, and registering a custom one:

#admin.py
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

admin.site.unregister(User)

class MyUserAdmin(UserAdmin):
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2')}
        ),
    )

admin.site.register(User, MyUserAdmin)
like image 109
Brandon Avatar answered Oct 13 '22 22:10

Brandon