Python Django Authentication Users and Authorization Custom Permission

App name

Hello! has_perm documentation says it requires app_name.permission. What is the app name for this task? I'm not sure if this is the reason why my code doesn't work, but this is the only idea I have for now

products/models.py
from django.core.urlresolvers import reverse
from django.db import models


class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField()
    discount = models.DecimalField(blank=True, null=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("products:detail", kwargs={"pk": self.pk})


    class Meta:
        permissions = (
            ("can_give_discount", "Can"),
        )
products/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic

from . import models


class List(generic.ListView):
    model = models.Product


class Detail(generic.DetailView):
    model = models.Product


class Create(LoginRequiredMixin, generic.CreateView):
    fields = ("name", "description", "discount", "price")
    model = models.Product

    def form_valid(self, form):
        if not self.request.user.has_perm("can_give_discount"):
            self.object.discount = 0.0
            self.object.save()
        return super(Create, self).form_valid(form)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,933 Points

You are very close! Need to fix the following items:

:point_right: Add definition of self.object

        self.object = form.save(commit=False)  # <-- add

:point_right: Add missing products' tohas_perm` argument

        if not self.request.user.has_perm("products.can_give_discount"):  # <-- add 'products'

:point_right: Unindent self.object.save() to be outside of the if code