gpt4 book ai didi

django - 在管理 Django 中扩展新用户表单

转载 作者:行者123 更新时间:2023-12-02 11:39:05 28 4
gpt4 key购买 nike

我通过完成制作用户配置文件应用程序和扩展用户模块的整个过程,为用户添加了一个额外的字段。

看起来没有错误。我无法弄清楚或在任何地方找到的是如何在管理员创建新用户的页面中显示这个新字段。因此,在名字和姓氏等个人信息下,我希望有一个添加到用户个人资料中的位置字段。

我的用户个人资料:

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 文件夹中的用户模型更改为:

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

根本没用。

[更新]这是我创建的 admin.py 帽子。我应该将其包含在 settings.py 文件中的哪里,以便它实际上使用带有添加的用户模块和新表单的文件夹?我有这条线,但它似乎根本没有使用新的形式AUTH_PROFILE_MODULE = '用户配置文件.用户配置文件'(我有一个名为 UserProfile 的文件夹,其中包含两个代码片段)

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 属性以更改显示的字段。 See this Stack Overflow question for an example.

如果您想与用户同时编辑 UserProfile 实例,一种方法是将 UserProfile 作为内联添加到您的自定义 UserAdmin。希望对您有所帮助。

为用户取消注册内置模型管理员并注册自定义模型管理员的示例:

#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 - 在管理 Django 中扩展新用户表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858028/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com