gpt4 book ai didi

django - 如何创建自己的扩展用户表单?

转载 作者:行者123 更新时间:2023-12-02 01:20:27 25 4
gpt4 key购买 nike

我有扩展 User 的 django 模型:

class Student(models.Model):
user = models.OneToOneField(User, unique=True)
#other field in that profile
#other field in that profile
#other field in that profile

在settings.py中添加:

AUTH_PROFILE_MODULE = 'myapp.Student'

现在我想在我的网站上有某种形式来创建该学生用户。最简单的方法是什么?我不知道我是否应该在 forms.py 中创建 ModelForm、forms.Form 或其他内容。我也不知道如何在views.py 文件中验证此表单。我只想添加具有该学生额外字段的新用户。我仍在尝试一些方法,但没有任何效果!请帮忙!

我使用的是Django1.2.5

最佳答案

您打算让您的用户通过管理网站访问此表单吗?

如果是这样,那么组合两种表单(用户和学生)的最简单解决方案是在管理站点中使用内联模型。

解决方案 1(最简单 - 使用管理站点,as document here):

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

from testapp.myauth.models import Student
from testapp.myauth.forms import UserForm

class StudentInline(admin.StackedInline):
model = Student

class MyUserAdmin(UserAdmin):
inlines = [
StudentInline,
]

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

现在,如果您不喜欢该解决方案,因为它看起来不漂亮,或者您不使用管理站点,您可以采用困难的方式来实现,并将两种形式无缝结合(您不会看到这是两种不同的形式)。这个方法源自这个great snippet .

解决方案2(更高级的方法——无缝表单组合):

models.py

class Student(models.Model):
user = models.OneToOneField(User, unique=True)
address = models.CharField(max_length=10)

# Create student instance on access - very useful if you plan to always have a Student obj associated with a User object anyway
User.student = property(lambda u: Student.objects.get_or_create(user=u)[0])

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm

from testapp.myauth.models import Student

class StudentForm(forms.ModelForm):
class Meta:
model = Student

class UserForm(UserChangeForm):
class Meta:
model = User

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
student_kwargs = kwargs.copy()
if kwargs.has_key('instance'):
self.student = kwargs['instance'].student
student_kwargs['instance'] = self.student
self.student_form = StudentForm(*args, **student_kwargs)
self.fields.update(self.student_form.fields)
self.initial.update(self.student_form.initial)

# define fields order if needed
self.fields.keyOrder = (
'last_name',
'first_name',
# etc
'address',
)


def clean(self):
cleaned_data = super(UserForm, self).clean()
self.errors.update(self.student_form.errors)
return cleaned_data

def save(self, commit=True):
self.student_form.save(commit)
return super(UserForm, self).save(commit)

所以我在这里所做的是在 UserForm 中创建 StudentForm 实例,并相应地组合它们的字段。

我给您的唯一建议是考虑将您的个人资料模型重命名为更通用的名称而不是学生(例如 UserProfile 可以),因为您永远不知道将来是否可能会拥有不同类型的用户、其他学生(例如老师)。

关于django - 如何创建自己的扩展用户表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5498152/

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