Extending the user profile in Django. Admin creation of users

馋奶兔 提交于 2019-12-18 17:27:21

问题


Good evening,

I am presently creating a site with Django and I extended the user with a user profile. I have a small problem though. Here is my situation:

  1. I extended the user profile in order to add custom fields.
  2. I added the model to the User Admin Model, so when I am adding a user, I can fill in directly the fields to create the profile.
  3. Now, if I don't add ANYTHING in these new custom user fields, in the user add page, Django Admin won't throw me an error saying these fields are null (and they aren't suppose to be)
  4. I want it to throw me an error in this User Add Admin page, so that the admins will HAVE to fill in a profile when adding a new user.
  5. ALL the users will be added in the Admin Panel.

Is this possible? Thanks a lot!

in admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.contrib.auth.models import User
from accounts.models import UserProfile


class UserProfileInline(admin.TabularInline):
    model = UserProfile


class UserAdmin(DjangoUserAdmin):
    inlines = [ UserProfileInline,]


admin.site.unregister(User)
admin.site.register(User, UserAdmin)

In model.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    employee_number = models.PositiveIntegerField(unique=True)

    def __unicode__(self):
        return 'Number'

回答1:


By default, empty inline is permitted and thus no further check would be taken for an empty form. You need to override it manually:

class UserProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.instance.pk is None:
            self.empty_permitted = False # Here

    class Meta:
        model = UserProfile


class UserProfileInline(admin.TabularInline):         
    model = UserProfile                               
    form = UserProfileForm  


来源:https://stackoverflow.com/questions/10213020/extending-the-user-profile-in-django-admin-creation-of-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!