在Django中不起作用get_context_data

时间:2015-07-24 08:05:18

标签: python django django-users

我使用具有两个实体的自定义用户模型:

class WeddyUser(AbstractBaseUser):
    username = models.CharField(
    'Юзернейм',
    max_length=50,
    unique=True,
    db_index=True
    )
    email = models.EmailField(
    'Электронная почта',
    max_length=255,
    blank=True,
    null=True
   )
    is_vendor = models.BooleanField(
    'Волшебник',
    default=False
   )
   #other atributes and methodes

此类由其他两种用户类型继承:

class Vendor(WeddyUser):
   org_name = models.CharField('Название организации', max_length=50, blank=True)
   slug = models.SlugField('Короткое название', unique=True)
   city = models.ForeignKey(City, null=True, blank=True)
   description = models.TextField('О себе', blank=True)

class PlainUser(WeddyUser):
    date_of_birth = models.DateField('Дата рождения', null=True, blank=True)
    favor_news = models.ManyToManyField('news.News',  blank=True)
    favor_pic = models.ManyToManyField('news.Photo', blank=True)

我尝试为这类用户构建个人区域:

在网址中:

url(r'^desktop/$', views.DesktopView.as_view(), name='desktop'),
模板中的

"{% url 'desktop'  %}" 

在视图中:

class LoginRequiredMixin(object):

@classmethod
def as_view(cls, **initkwargs):
    view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
    return login_required(view)


class DesktopView(LoginRequiredMixin,DetailView):
    model = WeddyUser
    context_object_name = 'weddyuser'

def get_context_data(self, **kwargs):
    context = super(DesktopView, self).get_context_data(**kwargs)
    if self.request.user.is_vendor:
        context['vendor']= Vendor.objects.get(id=self.request.user.id)
    context['plainuser']= PlainUser.objects.get(id=self.request.user.id)
    return context

def get(self, request, *args, **kwargs):
    c = {}
    c.update(csrf(request))
    user = request.user
    if user.is_vendor:
        return render_to_response('user/vendor_edit_profile.html', RequestContext(request, c))
    return render_to_response('user/user_edit_profile.html', RequestContext(request, c))

但是,我无法访问'vendor''plainuser'个上下文对象,'weddyuser'上下文也无效。我想我的get函数渲染模板没有任何上下文对象

1 个答案:

答案 0 :(得分:0)

更改此代码,

context['vendor']= Vendor.objects.get(id=self.request.user.id)
context['plainuser']= PlainUser.objects.get(id=self.request.user.id)

到此,

context['vendor']= Vendor.objects.get(weddyuser_ptr_id=self.request.user.id)
context['plainuser']= PlainUser.objects.get(weddyuser_ptr_id=self.request.user.id)

在return语句中传递上下文数据,

return render_to_response('user/vendor_edit_profile.html', self.get_context_data() ,RequestContext(request, c))
return render_to_response('user/user_edit_profile.html', self.get_context_data(), RequestContext(request, c))