How create a custom permission for a model?

186 views
Skip to first unread message

YusufSalahAdDin

unread,
Aug 31, 2014, 11:55:22 PM8/31/14
to django...@googlegroups.com
Hi, how are you?

I have the next question:

Good Nights, this is a question, not a issue.

I need have to user's types: a default admin in django, and a author.
Default admin have a aditional permission: can publish a news.
And for author user i have the next constrains:

  • Can't publish news.
    • Can't create other users
    • Can't create other topics or subtopics
    • Can create a new, but, only can edit or delete his own news, no other user's news.

I talked with other friend and he say me that i need per-objetcs permissions, but, i don't know how do this.

Can you help me?


Now i'm ussing django-permission, but i don't know how do a custom can_publish permission.


I wan't cread a custom view, no, i want used django's admin, news model have a boolean field, is_published, i want that if the user is Author, can modify this field, and if is admin, can modify this field, can anyone help me?

Collin Anderson

unread,
Sep 1, 2014, 1:07:19 PM9/1/14
to django...@googlegroups.com
> Can't create other users
> Can't create other topics or subtopics
These can be done using built in permissions and groups

Something like this might work for the rest:

class NewsAdmin(models.Model):

   
def get_queryset(self, request):
        queryset
= super(NewsAdmin, self).get_queryset(request):
       
if request.user.groups.filter(name="Author").exist():  # is the user an author?
             queryset
= queryset.filter(author=self.user)  # only allow users to edit their own posts
       
return queryset

   
def get_readonly_fields(self, request, obj=None):
        readonly_fields
= super(NewsAdmin, self).get_readonly_field(request, obj)
       
if request.user.groups.filter(name="Author").exist():  # is the user an author?
            readonly_fields
+= ['published']  # don't allow authors to change the publish status
       
return readonly_fields



YusufSalahAdDin

unread,
Sep 2, 2014, 8:54:40 PM9/2/14
to django...@googlegroups.com
Wel wel wel, my code is it :

class New(models.Model):
    author
= models.ForeignKey(User, verbose_name='Autor', related_name='news')
    content
= RichTextField(verbose_name='Contenido')
    created_date
= models.DateTimeField(auto_now_add=True, verbose_name='Fecha y Hora')
    is_published
= models.BooleanField(verbose_name='Publicada', default=False,) #Nueva, para verificar si se publica o no
    keywords
= models.ManyToManyField(KeyWord, blank=True, verbose_name='Palabras Clave', related_name='news')
    place
= models.CharField(max_length=255, verbose_name='Lugar')
    source
= models.URLField(verbose_name='Fuente', blank=True)
    subtopic
= models.ForeignKey(Subtopic, verbose_name='Subtema', related_name='news') #Filtramos por Opinion para sacar todas las columnas
    times_viewed
= models.PositiveIntegerField(default=0, editable=False, verbose_name='Veces Vista' )
    title
= models.CharField(verbose_name='Título', max_length=255, unique=True)
    slug
=  models.SlugField(verbose_name='Slug', max_length=100, unique=True)
    topic
= models.ForeignKey(Topic, verbose_name='Tema', related_name='news', )


   
class Meta:
        ordering
= ['-created_date']
        verbose_name_plural
= 'Noticias'
        verbose_name
= 'Noticia'


        permissions
= (
           
("can_publish", "Puede publicar noticias"), #Can publish news
       
)

from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic, StaffPermissionLogic
add_permission_logic
(New, AuthorPermissionLogic(
    field_name
='author',
    any_permission
=False,
    change_permission
=True,
    delete_permission
=True,
))
add_permission_logic
(New, StaffPermissionLogic(
    any_permission
=False,
    change_permission
=True,
    delete_permission
=True,
))


As you can see, i'm using django-permission.

What have i do ?

YusufSalahAdDin

unread,
Sep 2, 2014, 10:51:34 PM9/2/14
to django...@googlegroups.com
Hi men, now i have my model is thus:

from django.core.mail import send_mail, mail_admins


from django.db import models
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User


from ckeditor.fields import RichTextField


from subtopic.models import Subtopic
from topic.models import Topic
from keywords.models import KeyWord


#Global Vars




# Create your models here.



class New(models.Model):
    author
= models.ForeignKey(User, verbose_name='Autor', related_name='news')
    content
= RichTextField(verbose_name='Contenido')
    created_date
= models.DateTimeField(auto_now_add=True, verbose_name='Fecha y Hora')
    is_published
= models.BooleanField(verbose_name='Publicada', default=False,) #Nueva, para verificar si se publica o no
    keywords
= models.ManyToManyField(KeyWord, blank=True, verbose_name='Palabras Clave', related_name='news')
    place
= models.CharField(max_length=255, verbose_name='Lugar')
    source
= models.URLField(verbose_name='Fuente', blank=True)
    subtopic
= models.ForeignKey(Subtopic, verbose_name='Subtema', related_name='news') #Filtramos por Opinion para sacar todas las columnas
    times_viewed
= models.PositiveIntegerField(default=0, editable=False, verbose_name='Veces Vista' )
    title
= models.CharField(verbose_name='Título', max_length=255, unique=True)
    slug
=  models.SlugField(verbose_name='Slug', max_length=100, unique=True)
    topic
= models.ForeignKey(Topic, verbose_name='Tema', related_name='news', )


   
class Meta:
        ordering
= ['-created_date']
        verbose_name_plural
= 'Noticias'
        verbose_name
= 'Noticia'


        permissions
= (
           
("can_publish", "Puede publicar noticias"), #Can publish news
       
)


 
  def first_image(self):
       
return self.images.first() # Siendo images el related_name en Image


   
def first_video(self):
       
return self.videos #Devuelve el video de la imagen


   
def get_absolute_url(self):
       
return reverse ('NewsDefaultView', args = [str(self.created_date.strftime("%Y")), str(self.created_date.strftime("%m")), str(self.created_date.strftime("%d")), str(self.slug)])


   
def get_all_keys(self):
        keys_list
= self.keywords.values_list('name', flat=True)
       
return str(keys_list).strip("'[]'").replace("'",'')


   
#def is_published(self): devuelve si la noticia ha sido pulicada para que salga en la lista de noticias


   
def __str__(self):
       
return self.title


   
def save(self):  #Definir metodo para guardar, validar y otros metodos del Slug
       
super(New, self).save() #Solo con este me funciona correctamente
       
if not self.id:
           
self.slug = slugify(self.title)
       
super(New, self).save()


   
def get_queryset(self, request):
        queryset
= super(New, self).get_queryset(request)

       
if request.user.groups.filter(name="Author").exist():  # is the user an author?
             queryset
= queryset.filter(author=self.user)  # only allow users to edit their own posts
       
return queryset


   
def get_readonly_fields(self, request, obj=None):

        readonly_fields
= super(New, self).get_readonly_field(request, obj)

       
if request.user.groups.filter(name="Author").exist():  # is the user an author?

            readonly_fields
+= ['is_published']  # don't allow authors to change the publish status
       
return readonly_fields


from django.db.models.signals import post_save
def send_notification(sender, **kwargs):
       
return   mail_admins('Nueva noticia espera por edición','Una nueva noticia ha sido creada y espera ser editada y publicada muy pronto, anda, te esperamos.', )


post_save
.connect(send_notification, sender=New)



from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic, StaffPermissionLogic
add_permission_logic
(New, AuthorPermissionLogic(
    field_name
='author',
    any_permission
=False,
    change_permission
=True,
    delete_permission
=True,
))
add_permission_logic
(New, StaffPermissionLogic(
    any_permission
=False,
    change_permission
=True,
    delete_permission
=True,
))


from django.core.cache import cache
from django.db.models.signals import post_save
from django.dispatch import receiver


from django.contrib.sessions.models import Session
@receiver(post_save)
def clear_cache(sender, **kwargs):
   
if sender != Session:
        cache
.clear()

But, don't works, the author user can change other news and can publish :'(, what i'm doing bad?

I can created a group in python code? in models.py or other file or only can created a group in django admin?

YusufSalahAdDin

unread,
Sep 3, 2014, 1:58:53 PM9/3/14
to django...@googlegroups.com
Don't works for me :'(


El lunes, 1 de septiembre de 2014 12:07:19 UTC-5, Collin Anderson escribió:
Reply all
Reply to author
Forward
0 new messages