0

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

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))

虽然在语法上这是正确的,但现在我不知道如何在我的 url 中实际传递这个用户上下文。早些时候,我尝试只传递用户 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()
4

2 回答 2

3

它通常是这样工作的:

网址.py

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

视图.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))
于 2011-12-07T18:18:20.510 回答
2

您可以通过request.user简单地访问视图中的用户。同样,您也可以在请求对象中发布数据。

于 2011-12-07T18:08:17.290 回答