7

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)
Angie
  • 313
  • 1
  • 8
  • 20

1 Answers1

20

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)
Community
  • 1
  • 1
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • I am sorry, I am only trying to implement this now, since i didnt have time before and i am getting myself confused because of all the links. I am guessing i need to create a new file .py with the code for class MyUserAdmin(UserAdmin): you specified in http://stackoverflow.com/questions/6628452/how-can-i-have-django-user-registration-single-step-instead-of-two-stepprocess/6630174#6630174 ? – Angie Aug 02 '11 at 13:35
  • I updated my code, but not sure how to make my website to actually use it. So far its just a folder with .py files that arent linked to the main project – Angie Aug 03 '11 at 09:03
  • 1
    I added an example of how to register your custom user admin. – Brandon Taylor Aug 03 '11 at 14:18
  • That didn't seem to help at all. Currently what i have is a folder called UserProfile that contains a models.py and an admin.py. I have a feeling that this code isn't being used at all. Is there a line of code that I must include in the settings.py for it to use the UserProfile? – Angie Aug 04 '11 at 08:48
  • You'll need to add the app to your installed apps in settings.py in order for it to work. – Brandon Taylor Aug 04 '11 at 18:38
  • Awesome! Glad I could help you out. – Brandon Taylor Aug 05 '11 at 12:36