1

好的,所以我是 Django 的新手(并且通常进行编程,并且我正在构建一个需要多种用户类型的网站。我创建了一个我在 AUTH_PROFILE_MODULE 中拥有的基类,并且从基类继承了不同的用户类型。我的问题是如何访问从模板中继承自基类的类保存的数据。我知道我可以将 user.get_profile.field 用于基类中的任何内容,但它不适用于字段我在基类之外。如果你能看到我的代码,可能会更容易理解......

模型.py

class BaseProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    #Other common fields
    ...

class StudentProfile(BaseProfile):
    user_type = models.CharField(max_length=20, default="student")
    #Other student specific fields
    ...

class InstructorProfile(BaseProfile):
    user_type = models.CharField(max_length=20, default="instructor")
    #Other instructor specific fields
    ...

设置.py

AUTH_PROFILE_MODULE = 'signup.BaseProfile'

我有针对教师和学生的单独表格,并且每个表格中都有 user_type 作为 HiddenInput 字段,因此用户无法更改它,因此它默认为我想要的。我还设置了我的信号以适应我需要的不同表单信息。我可以在管理员中看到我的信号将成功地将 user_type 分别保存为“instructor”或“student”,具体取决于使用的表单,但我不知道如何在我的模板中检索它。我尝试了几种变体,包括:

模板.html

{% if user.get_profile.user_type == "instructor" %}
{% if user.user_type == "instructor" %}
{% if user.InstructorProfile.user_type == "instructor" %}

再说一次,我对一般编程很陌生,而不仅仅是 Python,所以如果我没有提供足够的信息或解释清楚,请原谅我。提前感谢您的帮助。如果我需要提供任何其他信息,请告诉我。我无法通过搜索找到答案。

4

2 回答 2

0

The first variation would be the right one, but the problem is that your user_type field is on the subclass, not the base class. When you do get_profile, you only get the base class, as Django has no way of knowing simply from the database what sort of subclass you are expecting.

Rather than putting the user_type field on the subclass and setting a default, put it in the base class, and override your save method to set it appropriately.

于 2012-09-04T15:21:47.700 回答
0

You could look at django-polymorphic. It provides a nice mechanism for this sort of thing.

于 2012-09-13T19:25:49.047 回答