-1

我有博客系统,每个用户都有自己的主页;

127.0.0.1/用户名

每个用户的登录屏幕位于:127.0.0.1/username/panel

这里又是他们的管理面板:127.0.0.1/username/admin

在登录页面中;当我提交时;它必须将用户重定向到管理面板。

但我需要访问目前在 url 中的用户名。我想我应该使用正则表达式。但如何?我对正则表达式不好。

这是我的 urls.py:

urlpatterns = patterns('blog.views',
    url(r'^blog/(?P<username>[-\w]+)/$',view='index', name='index'),
    url(r'^blog/(?P<username>[-\w]+)/post/(?P<postslug>[-\w]+)',view='singlePost', name='view_blog_post'),
    url(r'^blog/(?P<username>[-\w]+)/panel/$', view='loguserin'),
    url(r'^blog/(?P<username>[-\w]+)/admin/$', view='adminView', name='admin'),
    url(r'^blog/(?P<username>[-\w]+)/admin/loggedout/$', view='logout', name='logout'),
    url(r'^blog/(?P<username>[-\w]+)/admin/addpost/$', view='addpost',name='addpost'),
    url(r'^blog/(?P<username>[-\w]+)/admin/editpost/(?P<post_id>\d+)', view='editPost', name='editpost'),
    url(r'^blog/(?P<username>[-\w]+)/admin/delete/(?P<post_id>\d+)', view='delete_post', name='deletePost'),

)

这是我的views.py [登录部分]:

def loguserin(request,username):
    if request.method=='POST':
        uname = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=uname, password=password)
        form = LoginForm(request.POST)
        if form.is_valid():
            if user is not None:
                request.session['loggedin']="djangoo"
                login(request, user)
                return HttpResponseRedirect('/admin/') #--> ????
    else:
        form = LoginForm()

    return render_to_response('login.html',{'form':form,},context_instance=RequestContext(request))
4

2 回答 2

3

实际上,您已经有了用户名:

from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('admin', args=[uname]))
于 2012-09-13T15:12:56.803 回答
1

你需要的是反向参数:

from django.core.urlresolvers import reverse

def loguserin(request,username):
    if request.method=='POST':
        uname = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=uname, password=password)
        form = LoginForm(request.POST)
        if form.is_valid():
            if user is not None:
                request.session['loggedin']="djangoo"
                login(request, user)
                return HttpResponseRedirect(reverse('admin', args=[uname])) #--> ????
    else:
        form = LoginForm()

    return render_to_response('login.html',{'form':form,},context_instance=RequestContext(request))
于 2012-09-13T15:16:16.573 回答