Django:使用Request将Queryset添加到App View

时间:2013-07-15 19:53:59

标签: django view filtering django-queryset

这是我other question关于如何在app(Userena)视图中包含其他查询集(带请求)的延续。如果我执行@limelights建议的操作,这就是我的代码:

视图:

from django.views.generic import list_detail

def requestuserswampers(request):
     qs = Thing.objects.filter(user=request.user)
     return list_detail.object_list(
                 request,
                 queryset = Thing.objects.all(),
                 template_object_name = 'thing',
                 extra_context = {'swamp_things': qs},
     )

URL:

url(r'^accounts/(?P<username>(?!signout|signup|signin)[\.\w-]+)/$',
       requestuserswampers,
       name='userena_profile_detail'),

这会产生TemplateDoesNotExist错误:Template does not exist at myapp/swamp_things.html

如果我尝试使用template_name = 'userena/profile_detail.html'包含模板名称和位置,另一方面,会渲染正确的模板,但现在缺少某些上下文,例如通常在默认userena“profile_detail”模板..

如何向Userena配置文件详细信息视图添加额外的查询集,该视图允许请求以便我可以根据登录用户过滤对象?谢谢你的想法!

1 个答案:

答案 0 :(得分:0)

我没有意识到重新编写另一个应用程序的观点是公认的做法,认为这与DRY原则是对立的。但由于我没有发现另一种方法来实现我需要做的事情,并且由于它在上面的评论中得到了另一位高级用户的认可,所以我继续尝试重新编写Userena视图。只需将我的查询集添加到extra_context

def profile_detail(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):

    user = get_object_or_404(get_user_model(),
                         username__iexact=username)

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        return HttpResponseForbidden(_("You don't have permission to view this profile."))
    if not extra_context: extra_context = dict()
    extra_context['profile'] = user.get_profile()
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL

        #### Added the line below
    extra_context['swamp_things'] = Thing.objects.filter(user=user) 

    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)