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

What's the best approach to make content types user-limited in Django?

Let's say I want all users with the "blogger" user role to have their own blog.

I have created a weblog application. How do I restrict it so that the user is logged in, can only post to their "own" blog, and how do I create views that only show the user's blog?

0


source to share


2 answers


First, your blog posts need to be attached to a user, so you know which blog it appears on, right? models.py:

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

      

Then run it in ModelForm, forms.py:

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

      

Then when a user wants to post a post, you need them to register, 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()

      

If you want to display some user blog view.py:

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

      

User - django.contrib.auth.models.User You can add a personalized role check to the views above to display a 404 page page or an error page if the user does not have permission to create a blog.

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

+4


source


I didn't try to implement this, but I found another soul that worked really well. It was easy to implement and do whatever I wanted.



Check it...

-1


source







All Articles