Search code examples
djangouser-controlsblogsrestriction

One blog for each Django user with the "blog role"


What approach is the best way to make content-types restricted to a user in Django?

Let us say I want all users with the user-role "blogger" to have its own blog.

I have created a weblog app. How do I restrict it so that the user logged in can only post in his "own" blog, and how do I make views that shows only a user's blog?


Solution

  • First your blog entries has to be attached to user, so you know on whos blog display, it, right? models.py:

    class BlogEntry(models.Model):
        user = models.ForeignKey(User, related_name='blog_entries')
        other_field_1 = ...
        other_field_2 = ...
    

    Next, skip it in ModelForm, forms.py:

    class BlogEntryModelForm(forms.ModelForm):
        class Meta:
            exclude = ('user',)
    

    Then, when user want to post entry you require he's logged, views.py:

    @login_required
    def post_blog_entry(request):
        ....
        if request.method == 'POST':
           form = BlogEntryModelForm(request.POST)
           if form.is_valid():
              new_entry = form.save(commit=False)
              new_entry.user = request.user
              new_entry.save()
    

    When you want display some user blog, views.py:

    def view_blog(request, blogger_name):
        user = get_object_or_404(User, username=blogger_name)
        entries = user.blog_entries.all()
    

    User is django.contrib.auth.models.User You can add custom role checking to views above to display 404 page or error page if user has no rights to create blog.

    Optionally you can replace User from django.contrib.auth with your own User implementation but you'll have to write model, authentication and middleware for it as well...