[Django]-Django, getting url parameter into view

5👍

The positional and named parameters are stored in self.args and self.kwargs respectively, so you can access it with:

class CompanyAdminView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):

    # ...

    def test_func(self):
        company = Company.objects.filter(crn=self.kwargs['company_spec_url'])[0]
        return company.admin == self.user

Note that the above can be tricky: here if multiple companies have the same crn, then you will let a (possibly random) order decide what company you pick, and whether that admin is the self.user. Furthermore it will here result in two queries.

class CompanyAdminView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):

    # ...

    def test_func(self):
        return Company.objects.filter(
            crn=self.kwargs['company_spec_url']
            admin=self.user
        ).exists()

With the above we check if there is a Company that has as crn the parameter in the URL, and self.user as admin.

Leave a comment