Python Django Authentication Users and Authorization Custom Permission

Eric Shelby
Eric Shelby
24,617 Points

Custom Permission Challenge

According to the instructions:

"Now override the form_valid method for the Create view. If the user (self.request.user) does not have the right permission (check with has_perm), set the saved object's (self.object) discount to 0. Be sure to resave the object!"

I tried a few configurations, but nothing works. Permission without the right authorization still get through. Is there something I'm missing?

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", "hi_there"),
        )
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):
    resp = super().form_valid(form)
    if not self.request.user.has_perm("products.can_give_discount"):
        self.object.discount = 0
        self.object.save()
    return resp

1 Answer

Michael ‍
Michael ‍
Python Web Development Techdegree Graduate 14,108 Points
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("products.can_give_discount"):
            obj = form.save(commit=False)
            obj.discount = 0
            obj.save()
        return super(Create, self).form_valid(form)