[英]show different content based on logged in user django
So I just learned Python/Django last weekend.所以我上周末刚学了 Python/Django。 What I'm trying to do is have url routes available with different content depending on who's logged in. So my usecase is I create 5 usernames/passwords and then those 5 users can login to read specific content/routes catered to them that no other user should be able to see.我想要做的是根据登录的人提供具有不同内容的 url 路由。所以我的用例是我创建 5 个用户名/密码,然后这 5 个用户可以登录阅读特定的内容/路由以满足他们的需求用户应该能够看到。
Right now I have these routes with correlating views.现在我有这些具有相关视图的路线。
urlpatterns = [
url(r'^$', accounts.views.loginview),
url(r'^accounts/', include('accounts.urls')),
url(r'^sitepages/', include('sitepages.urls')),
]
I get the auth thing, I'm filtering content to only logged in users using @login_required, it looks like this :我得到了身份验证的东西,我正在过滤内容以仅使用@login_required 登录用户,它看起来像这样:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def attributes(request):
return render(request, 'sitepages/something.html')
I've researched how to have a different menu bar depending on the user, etc. But I haven't been able to find how to have entirely different routes and content pages depending on the user.我已经研究过如何根据用户等设置不同的菜单栏。但我一直无法找到如何根据用户拥有完全不同的路线和内容页面。
I think I'll need to do this using groups in Django and I think that I'll need to use the user's foreign key in order to cater the content.我想我需要在 Django 中使用组来做到这一点,我认为我需要使用用户的外键来满足内容。 I created one group using admin, but I'm having a hard time consolidating my next step.我使用 admin 创建了一个组,但我很难整合我的下一步。
These are the resources I've checked out:这些是我检查过的资源:
Django Database routing based on current user logged in 基于当前登录用户的Django数据库路由
Django restrict pages to certain users Django将页面限制为某些用户
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication
https://docs.djangoproject.com/en/1.10/topics/auth/default/ https://docs.djangoproject.com/en/1.10/topics/auth/default/
I'm on Python version 3.6.0;我使用的是 Python 3.6.0 版; Django version 1.10.6 Django 版本 1.10.6
My answer is based on assumption.我的回答是基于假设。 But these are also some general pointers, that should help you understand your options and more about django's way of model/url/view concept.但这些也是一些通用的指针,应该可以帮助您理解您的选择以及更多关于 django 的模型/url/视图概念的方式。
To store different content for users I would recommend creating a simple model in your models.py
to save everything in your database, with fields for title, content and a reference to the user it belongs too:为了为用户存储不同的内容,我建议在你的models.py
创建一个简单的模型来保存数据库中的所有内容,包括标题、内容和对它所属用户的引用的字段:
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField(max_length=50)
content = models.TextField(...)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
The slug field holds the title in a url-friendly format that you can look for in an url pattern as variable in your urls.py
: slug 字段以 url 友好格式保存标题,您可以在 url 模式中查找作为urls.py
变量:
urlpatterns = [
url(r'^(?P<user>\w+)/(?P<slug>\w+)/$', views.PageView.as_view(), name='page'),
...
]
It defines two placeholders so you can have urls like:它定义了两个占位符,因此您可以使用以下网址:
They will all be 'caught' by the same url pattern.它们都将被相同的 url 模式“捕获”。
Check how to create a simple Class-based TemplateView
in your views.py
.检查如何在您的views.py
创建一个简单的基于类的TemplateView
。 And use the collected url parameters (eg user sarah
and title apples
) to query the database for the corresponding page, then populate the template context with those values to fill your html template placeholders.并使用收集到的 url 参数(例如 user sarah
和 title apples
)查询相应页面的数据库,然后用这些值填充模板上下文以填充您的 html 模板占位符。
If different urls are not a requirement for you, you can also have different content served based on the current user with a url that does not need variables:如果您不需要不同的 url,您还可以根据当前用户使用不需要变量的 url 提供不同的内容:
url(r'^/profile/$', views.ProfileView.as_view(), name='profile'),
In your view you can pick the right page record like this then:在您看来,您可以像这样选择正确的页面记录,然后:
content = Page.objects.get(user=request.user).content
Another possibility is using GET parameters: eg /?page=intro
.另一种可能性是使用 GET 参数:例如/?page=intro
。 Then use Page.objects.get(title=request.GET.get("intro"))
to get the content from the database.然后使用Page.objects.get(title=request.GET.get("intro"))
从数据库中获取内容。 You can combine the last two as well.您也可以将后两者结合起来。
Update:更新:
To ensure that only the right user can access the page you can use a django shortcut:为了确保只有正确的用户才能访问该页面,您可以使用 django 快捷方式:
get_object_or_404(Page, slug=slug, user=request.user)
If will show a "Page not found" if the current user does not have a page named like this.如果当前用户没有这样命名的页面,则将显示“找不到页面”。 Eg if user jim
tries to access /anna/apple
he will get a 404 response while anna
can see her apple page.例如,如果用户jim
尝试访问/anna/apple
他将收到 404 响应,而anna
可以看到她的苹果页面。
I did something similar recently, and just implemented a simple higher-order function to do it.我最近做了类似的事情,只是实现了一个简单的高阶函数来做到这一点。 My use-case was to provide a separate view for a logged-in user from an unlogged-in user.我的用例是为登录用户和未登录用户提供单独的视图。
Simply write a wrapping function to select the view to render based on some parameters:只需编写一个包装函数来根据一些参数选择要渲染的视图:
def logged_in_switch_view(logged_in_view, logged_out_view):
def inner_view(request, *args, **kwargs):
if request.user.is_authenticated:
return logged_in_view(request, *args, **kwargs)
return logged_out_view(request, *args, **kwargs)
return inner_view
Then use it in the urlpatterns
:然后在urlpatterns
使用它:
from .views import LoggedInHome, PublicHome
from .view_wrappers import logged_in_switch_view
urlpatterns = [
path('', logged_in_switch_view(
LoggedInHome.as_view(), PublicHome.as_view()
)),
]
You could just tweak logged_in_switch_view
to look to see who the actual user is and switch appropriately, should be reasonably obvious.您可以调整logged_in_switch_view
以查看实际用户是谁并适当切换,应该相当明显。 The nice thing is that you should just be able to pass base views protected by @login_required
and get the same protection, as a double-check.好消息是您应该能够传递受@login_required
保护的基本视图并获得相同的保护,作为双重检查。
Seems to work quite well so far.到目前为止似乎工作得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.