views:

347

answers:

2

Hi,

What approach is the best way to make content-types restricted to a user in Django, lets say that i want all users with the user-role "blogger" to have its own blog.

Ive createt a weblog app, but how do i restrict it so that the user logged inn can only post in his "own" blog, and how do I make views that shows only a users blog?

Anybody got an idea?

+4  A: 

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...

romke
A: 

I didnt try to implement this, but I found another soultion that worked very good. It was easy to implement and did everything i wanted.

Check it out...

Espen Christensen
well, you asked how to make views, not how to modify admin views default behavior
romke
Yeah, i see that know, sorry..
Espen Christensen