我有两种类型的用户。用户登录后,我会将用户带到/ profile
中的用户个人资料根据用户类型,他们的个人资料可能包含不同的导航项和表单。是否有更简单的方法来构建基于用户类型的导航,而不是在模板中的任何位置放置{%if%}标记。
答案 0 :(得分:2)
不确定为什么@ dm03514删除了他的答案,但我会发布类似的内容,因为这也是我的想法。
如果模板足够不同,那么你是对的,在整个地方进行分支是一个坏主意。它只会使你的模板混乱。因此,只需为每种用户类型创建一个单独的模板。然后,在您的视图中,您可以根据用户类型选择一个或另一个模板进行显示。例如:
旧式基于功能的观点:
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))
基于类的新视图:
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模板,允许您分解一些常用功能。
答案 1 :(得分:1)
创建配置文件模型并将用户链接到此配置文件模型。 (通过外键)
然后,配置文件模型将针对不同的行为具有不同的属性。
然后,通过分支模板(如您在模板中使用if)或将不同数据返回到模板或将其发送到字体末端的javascript函数以修改行为,可以在Web应用程序中公开这些不同的行为。 / p>
另一种方法是根据个人资料将用户引导至不同的网页。对此的挑战是不同用户需要不同的URL。这可能会导致大量代码重复。
答案 2 :(得分:1)
您是否考虑过使用权限? 我也使用自定义权限。简单的部分是auth提供您需要的任何东西,它总是在请求中。
与Chris Patt建议使用的代码非常相似:
def profile_view(request):
if request.user.has_perm('permission_codename_foo'):
template = 'path/to/foo_profile.html'
elif request.user.has_perm('permission_codename_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))
有用的是,您可以使用装饰器使用相同的权限来保护您的视图:
@permission_required('permission_codename_foo')
def foo():
#your view here
或者如果您想检查许可替代方案:
#user_passes_test(lambda u: u.has_perm('permission_codename_foo') or u.has_perm('permission_codename_bar'))
def foo_or_bar():
#your view here
如果您需要限制用户的可能性,django会创建一大堆默认权限:app_name.add_modelname,app_name.change_modelname和app_name.delete_modelname
如果您需要更改部分模板,请尝试使用{%include%}从不同的文件中加载这些部分。