0

I am trying to implement a web app in django where I have a class based view that inherits from PermissionRequiredMixin and generics.View.

Here is an example model:

class SomeModel(models.Model):
    # Here I will put some model attributes

    class Meta:
        permissions = (
            ('some_permission', 'Can do some job'),
        )

Until now I am not confused yet. However, when I am trying to write the view, I am confused. I read some Stack Overflow questions and also the django documentation, but I did not understand well because they are writing something like this:

class MyView(PermissionRequiredMixin, View)
    permission_required = ('polls.can_open', 'polls.can_edit')

I tried to figure out what to write in my case, and I ended up in writing this:

class SomeView(PermissionRequiredMixin, View):
    permission_denied_message = 'You don\'t have permission'
    permission_required = 'app_name.some_permission'

What made me in doubt is that PyCharm did not auto-complete when I wrote the last line which is: permission_required = 'app_name.some_permission'. Also, I am not sure whether django will know which permission that I am talking about here.

Did I understand how to do the job? or I am wrong? Should I write it like this: permission_required = 'app_name.SomeModel.some_permission'?

Ambitions
  • 2,369
  • 3
  • 13
  • 24
  • 2
    Your view seems fine. Pycharm is a great IDE, but it might have limitations – JPG Apr 08 '20 at 08:04
  • 1
    Did you just test your code instead of relying on what your IDE might say ? Hint: PyCharm is often wrong ;-) – bruno desthuilliers Apr 08 '20 at 10:10
  • 1
    "lso, I am not sure whether django will know which permission that I am talking about here." => it will split the string on the dot and lookup the permissions table for a perm with "some_permission" codename belonging to "app_name" app. Note that Django is OSS so you can just read the code to find out how something is implemented ;-) – bruno desthuilliers Apr 08 '20 at 10:13
  • @brunodesthuilliers I didn't test it because I am just starting it, I have to implement some templates before being able to test this view. What I understood from your comment is that Django will create an instance in the permissions table whenever it sees a `permissions` attribute defined in `Meta` class defined in a model. Am I right? – Ambitions Apr 08 '20 at 14:34
  • @Ambitions you are right. This is (at least partly) documented FWIW, and you can have a look at the permissions table (and the `User.has_perm()` source code) for more details ;-) – bruno desthuilliers Apr 09 '20 at 06:22

0 Answers0