在我的项目中,我有两种不同类型的用户:教师和学生,每种用户都有自己的个人资料数据。
在搜索最佳方法之后,似乎前进的方法是使用多表继承:
class BaseProfile(models.Model):
user = models.OneToOneField(User)
profile = models.CharField (max_length=10, choices={'teacher', 'student'})
# other common fields
class Teacher(BaseProfile):
# teacher specific fields
class Student(BaseProfile):
# student specific fields
在settings.py
:AUTH_PROFILE_MODULE
= myapp.BaseProfile
.
现在我想实现与 django-profiles 相同的功能:
- 创建配置文件
- 编辑配置文件
- 显示配置文件
当我在BaseProfile
field profile
中具有正确的值时,我很清楚如何进行编辑和显示部分。
问题:
现在,我希望在使用信号创建用户时直接自动(并在正确的db:Teacher
或Student
)中自动完成配置文件的创建。当用户通过注册表通过网站注册时,字段profile
应包含值"student"。当管理员通过管理界面创建新用户时,该值应为"教师"。
有人知道我如何做到这一点吗?可能我需要编写一个自定义信号,如下所示,并从用户模型发送它,但还没有找到可行的解决方案:
def create_user_profile(sender, instance, request, **kwargs):
if request.user.is_staff:
BaseProfile(user=instance, profile='teacher').save()
else:
BaseProfile(user=instance, profile='student').save()
当然,也欢迎其他更好的方法!
谢谢!
这不是一个好方法。
我建议做 1 个统一的配置文件,其中包含一个选项:user_type = 模型。CharField(choices=[your_choices], max_length=4)
然后在模型中,您将创建两个表单 - 1 个用于教师,1 个用于学生。
class ProfileFOrm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseProfileForm, self).__init__(*args, **kwargs)
for name in self.fields:
self.fields[name].required = True
class TeacherProfile(ProfileForm):
class Meta:
model = Profile
fields = ('your_fields')
class StudentProfile(ProfileForm):
class Meta:
model = Profile
fields = ('school')
这只是我对那个:)的想法
编辑
简介版本:
视图。
def profile(request):
p = get_objects_or_404(ProfileModel, user=request.user)
return TemplateResponse(request, 'template.html', {'profile': p})
在模型中,我们需要一个函数来检查用户是学生还是老师,因此:
class Profile(models.Model):
... your fields here...
def get_student(self):
return self.user_type == 1
在模板中:
{% if profile.get_student%}
>>>>get all data for students ex: <<<<
{{profile.name}}
{% endif %}
{% if profile.get_teacher %}
....