Python Django Authentication Users and Authorization Custom Permission

Barry Hatfield
Barry Hatfield
3,001 Points

Struggling to set up discount permissions in form_valid method

I've gone through the docs, but am not sure how to implement has_perm()

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)

    class Meta:
        permissions = (
            ('can_give_discount','gives discount'),
        )

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("products:detail", kwargs={"pk": self.pk})
products/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from djando.contrib.auth import has_perm

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

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Your code looks like it should pass once you fix the indentation.

Barry Hatfield
Barry Hatfield
3,001 Points

Still no Joy: Manually added every space as I didn't want to trust the tab button. Am I indenting something incorrectly?

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

    def form_valid(self, form):
        user = self.request.user
        if not user.has_perm('products.can_give_discount'):
            self.object.discount = 0
        self.object.save()
        return super(form_valid, self).form_valid(form)

[MOD: added ```python formatting -cf]

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,428 Points

Hey Barry Hatfield, there are two errors in your code:

:point_right: Before the if statement, define the self.object:

        self.object = form.save(commit=False)  # <-- create self.object to modify

:point_right: Call the parent class from super() not the method:

        return super(Create, self).form_valid(form)  # <-- refer to the parent class

Otherwise, your code will pass. Post back if you need more help. Good Luck!!