0

我正在尝试在 django 1.3 中创建两种用户类型。我将 AUTH_PROFILE_MODULE 子类化为以下 models.py:

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'

知道可能缺少什么吗?

4

1 回答 1

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)
于 2011-05-27T22:58:15.670 回答