简体   繁体   English

逻辑网址格式-django | 蟒蛇

[英]Logical url patterns - django | python

I'm building a social network and I want to show special content when a user is logged in and he accesses to his public profile url (so i'll show customization tools). 我正在建立一个社交网络,我想在用户登录并显示其公共资料URL时显示特殊内容(因此,我将显示自定义工具)。 I've written code to return the user name and match it with the regex, but I don't know how to only have the pattern if the user is logged in. 我已经编写了返回用户名并将其与正则表达式匹配的代码,但是我不知道如何仅当用户登录后才具有该模式。

from django.conf.urls import patterns, include, url
import re
from auth import engine
profile_name = engine.get_profile_name()

urlpatterns = patterns('',
...

    url(r'^'+re.escape(profile_name)+r'/?', 'myprofile.views.show_profile') # authentication required
)

The engine will return None if the user is not logged in. But this may cause an error in url(). 如果用户未登录,引擎将返回None 。但这可能会导致url()错误。

So how can I achieve it? 那么我该如何实现呢?

You have to decorate either your view function or view class with login_required . 您必须使用login_required装饰视图函数或视图类。 There is no regex way to find out if the user is logged in or not since it's handled by the sessions and requests and not your url. 由于会话和请求(而不是您的网址)处理用户,因此没有正则表达式可以确定用户是否已登录。

You can read up on it here otherwise here's an example functional view 您可以在这里阅读,否则这里是一个示例功能视图

@login_required(login_url="/login/") #will redirect to login if not logged in.
def show_profile(request, profile_name):
   return render_to_response(...)

Or this is another approach if you want to omit the decorator 或者如果您想省略装饰器,则这是另一种方法

def show_profile(request, profile_name):
    if request.user.is_authenticated():
        return render_something_cool
    else:
        return render_something_else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM