show different content based on logged in user django

删除回忆录丶 提交于 2019-12-04 19:38:41

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.

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:

    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:

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:

  • /sarah/apples
  • /jim/bananas
  • /anna/apples

They will all be 'caught' by the same url pattern.

Check how to create a simple Class-based TemplateView in your views.py. And use the collected url parameters (e.g. 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.

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(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: e.g /?page=intro. Then use Page.objects.get(title=request.GET.get("intro")) to get the content from the database. 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:

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. E.g. if user jim tries to access /anna/apple he will get a 404 response while anna can see her apple page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!