在Django 1.3中访问SubClassed用户配置文件模块

时间:2011-05-27 22:11:53

标签: django django-class-based-views django-profiles

我正在尝试在django 1.3中创建两个用户类型。我正在使用以下models.py:

继承AUTH_PROFILE_MODULE
class Member(models.Model):
    ROLE_CHOICES = (
        (0, 'Guide'),
        (1, 'Operator'),
    )
    user = models.ForeignKey(User, unique=True)
    location = models.CharField(max_length=60)
    role = models.IntegerField(choices=ROLE_CHOICES)


class Guide(Member):
    bio = models.TextField(blank=True)
    experience = models.TextField(blank=True)
    image = models.ImageField(blank=True, upload_to='images')
    fileupload = models.FileField(blank=True, upload_to='files')

    def __unicode__(self):
        return self.user.username

    def get_absolute_url(self):
        return '/profiles/guides/%s' % self.user.username


class Operator(Member):
    bio = models.TextField(blank=True)
    image = models.ImageField(blank=True, upload_to='images')

    def __unicode__(self):
        return self.user.username

    def get_absolute_url(self):
        return '/profiles/operators/%s' % self.user.username

我正在使用基于通用类的视图,并且可以使ListView适用于Guide和Operator模型我无法使DetailView工作。我的views.py如下:

class GuideDetailView(DetailView):
    model = Guide
    context_object_name = 'guide'
    template_name = 'members/guide_detail.html'


class GuideListView(ListView):
    model = Guide
    context_object_name = 'guides'
    template_name = 'members/guide_list.html'

知道可能缺少什么吗?

1 个答案:

答案 0 :(得分:1)

提供查询集:

class GuideDetailView(DetailView):
    queryset = Guide.objects.all()

或覆盖DetailView的get方法:

class GuideDetailView(DetailView):
    def get(self):
        return "Everything you want, maybe: Guide.object.get(id=1)"

在你的urls.py中给出这个:

url(r'^(?P<my_id>\d)/$', GuideDetailView.as_view(),),

您需要覆盖get,如下所示:

class GuideDetailView(DetailView):
    def get(self, request, **kwargs):
        # lookup Guide Id in your database and assign it object
        self.object = Guide.objects.get(pk=kwargs.get('my_id'))
        # add object to your context_data, so that you can access via your template
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)