在管理员Django中扩展新的用户表单 [英] Extending new user form, in the admin Django

查看:148
本文介绍了在管理员Django中扩展新的用户表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为用户添加了一个额外的字段,通过进行用户配置文件应用程序和扩展用户模块的整个过程。

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.

我的用户个人资料:

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)

我也想知道如何使电子邮件强制,如密码和用户名。只需将Django文件夹中的用户模型更改为:

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)

根本没有工作。

[UPDATE]
所以这是我创建的我的admin.py帽子。
我应该在settings.py文件中包含哪些内容,以便实际使用该添加的用户模块和新表单的文件夹?
我有这行,但似乎没有使用新的表单
AUTH_PROFILE_MODULE ='UserProfile.UserProfile'
(我有一个名为UserProfile的文件夹,其中包含两个代码狙击手)从django.contrib导入admin
从django.contrib.auth.models导入用户,组


[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)


推荐答案

您需要使用自己的UserAdmin类并修改add_fieldsets属性以更改显示的字段。 请参阅此堆栈溢出问题作为示例。

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.

如果要在用户同时编辑UserProfile实例,一种方法是将UserProfile作为内联添加到您的自定义UserAdmin中。希望这有助于您。

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)

这篇关于在管理员Django中扩展新的用户表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆