gpt4 book ai didi

python - 根据用户类型显示不同的个人资料

转载 作者:太空宇宙 更新时间:2023-11-04 10:56:31 25 4
gpt4 key购买 nike

我有两种类型的用户。用户登录后,我将用户带到他们在/profile 的用户个人资料

根据用户的类型,他们的个人资料可能包含不同的导航项和表单。有没有更简单的方法来构建基于用户类型的导航,而不是在模板中到处放置 {% if %} 标签。

最佳答案

不知道为什么 @dm03514 删除了他的回答,但我会发布类似的内容,因为这也是我的想法。

如果模板足够不同,那么你是对的,到处分支是个坏主意。它只会让你的模板变得一团糟。因此,只需为每种用户类型创建一个单独的模板。然后,在您的 View 中,您可以根据用户类型选择一个或另一个模板来显示。例如:

旧式基于函数的 View :

def profile_view(request):
if request.user.get_profile().type == 'foo':
template = 'path/to/foo_profile.html'
elif request.user.get_profile().type == 'bar':
template = 'path/to/bar_profile.html'
else:
template = 'path/to/generic_profile.html' # if you want a default

return render_to_response(template, {'data': 'data'}, context_instance=RequestContext(request))

新型基于类的 View :

class MyView(View):
def get_template_names(self):
if self.request.user.get_profile().type == 'foo':
return ['path/to/foo_profile.html']
elif self.request.user.get_profile().type == 'bar':
return ['path/to/bar_profile.html']
else:
return ['path/to/generic_profile.html']

我不确定您的用户类型是如何设置的,但如果它基于字符串值,您甚至可以创建更加自动化的内容,例如:

 template = 'path/to/%s_profile.html' % request.user.get_profile().type

然后,只需根据该命名方案为每种类型创建一个模板。

当然,每个模板都可以扩展基本的 profile.html 模板,让您提取出一些通用功能。

关于python - 根据用户类型显示不同的个人资料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9421345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com