如何将用户实例传递给Django中的视图

时间:2011-12-07 18:05:42

标签: django django-views django-urls django-users

我正在创建一个博客应用,我想制作一个显示特定用户的所有博客的视图。为此,我需要将用户实例作为

传递给我的视图
def blogs(request,author=None,slug=None):

   # If the author context has been passed then display the blogs of that author 
   if author:

        # Displays a particular blog
        if slug:         
            this_blog = get_object_or_404(Entry, creator = author, slug = slug)
            return render_to_response('blog/blog_view.html', {'blog': this_blog,},context_instance=RequestContext(request))

        # Displays all the blogs of a particular user
        else:
            blog_list = Entry.objects.filter(creator = author)
            return render_to_response('blog/all_blogs_user.html', {'Blogs': blog_list},context_instance=RequestContext(request))

虽然从语法上说这是正确的,但现在我不知道如何在我的网址中实际传递这个用户上下文。之前我试过只传递用户ID,但这不起作用。做这件事还有其他选择。当我在内部构建url或重定向到此特定视图时,它很好,但是url如何在外部看起来像。我的urls.py是

from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    url(r'^$', 'blog.views.blogs', name='all_blogs'),
    url(r'^(?P<author>\d+)/(?P<slug>[-\w]+)/$', 'blog.views.blogs', name='view_blog'),                       
    url(r'^(?P<author>\d+)/(?P<slug>[-\w]+)/edit/$', 'blog.views.post_form', name='edit_blog'),
    url(r'^new/$', 'blog.views.post_form', name='new_blog'),
    url(r'^(?P<author>\d+)/(?P<slug>[-\w]+)/delete/$', 'blog.views.delete_blog', name='delete_blog'),

)
urlpatterns += staticfiles_urlpatterns()

2 个答案:

答案 0 :(得分:3)

它通常是这样的:

<强> urls.py

url(r'/author/(?P<slug>/$', 'author_index'),

<强> views.py

def author_index(request, slug):
    author = get_object_or_404(User, username=slug)

    return render_to_response('author_index.html', {
        'author': author,
    }, context_instance=RequestContext(request))

答案 1 :(得分:1)

您只需通过 request.user 访问视图中的用户即可。同样,您也可以在请求对象中 POST 数据。