Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Function Based View to Class Based View
How would I convert my Function Based View into Class Based View. urls.py urlpatterns = [ path('', views.SlideShowView, name="slideshow"), ] models.py class Carousel(models.Model): title = models.CharField(max_length=255, blank=True) description = models.TextField(max_length=255, blank=True) image = models.ImageField(upload_to="showcase/%y/%m/%d/", blank=True) def __str__(self): return self.title views.py def SlideShowView(request): carousel = Carousel.objects.all() context = { 'carousel' : carousel, } return render(request, "showcase.html", context) -
Forbidden (CSRF cookie not set.) Django
I'm trying to do an endpoint API. And for that, i'm using django. My url in urls.py is : path('tutorials/', tutorial_list_test.as_view()), and my views.py is like class tutorial_list_test(GuestOnlyView, FormView): print("test"); @api_view(['GET', 'POST', 'DELETE']) def tutorial_list(self): request = self.request; if request.method == 'POST': alldata=request.POST username = alldata.get("username", "0") print("POST name: " + username) return Response('The tutorial does not exist', status=status.HTTP_404_NOT_FOUND) But when i'm doing a request, i have everytime the same error "Forbidden (CSRF cookie not set.): /accounts/tutorials/" So I did some research, and I could see several proposed solutions. The first was to use csrf_exempt but it's not working for me: path('tutorials/', csrf_exempt(tutorial_list_test.as_view())), And it's the same for all the methods I used. Even if I remove this line from my settings.py, nothing changes # django.middleware.csrf.CsrfViewMiddleware', To test, I use Postman, but even using my angular front end, it does the same. const formData = new FormData() formData.append('username', this.username_signup); this.http.post('http://127.0.0.1:8000/accounts/tutorials/', formData) .map((data: Response) => { if (data !== null) { console.log(JSON.stringify(data)); }; }).subscribe(response => console.log(response)) I would like to know if you have any idea how I can do this. Because I need to be able to access my Models, so not using a class and directly making a def … -
How to Update Django Model Relationship only with Foreign Key Value
I'm looking for a way to update a relationship on a model in Django by only passing the foreign key value and not the model being referenced in the relationship. I understand that Django wants me to do this publisher = Publisher.objects.get(id=2) book = Book.objects.get(id=1) book.update(publisher=publisher) But I'm looking to just update the publisher using the publishers PK so something more along the lines of this. book = Book.objects.get(id=1) book.update(publisher=2) I have a significant amount of data that needs to get updated and I don't necessarily have a reference to what the model is for each field that needs to get updated on the "Book". -
Relation does not exist behavior in django + postgresql
After looking at all the other answers here I still can't figure this out. In my project I have two apps, the first app users manages users and the second one signals manages the contents to be displayed. Right now I am just trying to make the second app signals work but even the simplest models will throw errors in admin. The error i get: ProgrammingError at /admin/signals/signal/ relation "signals_signal" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "signals_signal" This is what I have in models.py: class Asset(models.Model): name = models.CharField(max_length=30) ticker = models.CharField(max_length=30) def __str__(self): return "%s, %s" % (self.name, self.ticker) class Signal(models.Model): type = models.CharField(max_length=100) date = models.DateField() asset = models.ForeignKey(Asset, on_delete=models.CASCADE) def __str__(self): return self.type In settings.py; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': BASE_DIR / 'db.sqlite3', 'NAME': 'users', 'USER': 'admin', 'PASSWORD': 'password', 'HOST': 'localhost' } } And the admin.py for signals is: from django.contrib import admin from .models import Asset, Signal # Register your models here. class AssetAdmin(admin.ModelAdmin): pass admin.site.register(Asset, AssetAdmin) class SignalAdmin(admin.ModelAdmin): pass admin.site.register(Signal, SignalAdmin) I have tried basically everything: deleting migrations, doing startapp from scratch etc. I have never used postgres before. Thank you for any assistance. -
ModuleNotFoundError: No module named 'django.core'
I want to create django project so I've configured virtualenv ,and I installed django pipenv install django==4.0.1 when I create app using this command python3 manage.py startapp Accounts I got this error. (env) zakaria@ZAKARIA:/mnt/c/Users/ZAKARIA/Desktop/project$ python manage.py startapp Accounts Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django.core' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? can any one help to solve this problem ? -
When I try to build docker in locally - Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects?
Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [41 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-310 creating build/lib.linux-x86_64-cpython-310/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-cpython-310/backports creating build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/__init__.pyi -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.linux-x86_64-cpython-310 creating build/temp.linux-x86_64-cpython-310/lib gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/usr/local/include/python3.10 -c lib/zoneinfo_module.c -o build/temp.linux-x86_64-cpython-310/lib/zoneinfo_module.o -std=c99 lib/zoneinfo_module.c: In function ‘zoneinfo_fromutc’: lib/zoneinfo_module.c:600:19: error: ‘_PyLong_One’ undeclared (first use in this function); did you mean ‘_PyLong_New’? 600 | one = _PyLong_One; | ^~~~~~~~~~~ | _PyLong_New lib/zoneinfo_module.c:600:19: note: each undeclared identifier is … -
Junction table referencing non existent entity
I have the following models in django class WorkSession(models.Model): pass class Invoice(models.Model): work_sessions = models.ManyToManyField(WorkSession, blank=True) what I noticed is that when i do the following: invoice = Invoice() session = WorkSession(a=a, b=b) invoiceo.work_sessions.set([session]) The invoice_worksession junction table gets populated with a relation, even though I haven't saved invoice yet. Meaning that the invoices table, there's no row, but in the junction table, there's a row that references an invoice that doesn't exist yet. Is this normal ? Because this is causing an integrity error on fixture teardown since the invoice doesn't exist and yet, there's a refrence to an invoice id in the junction table -
Why javascrpt does not select the button?
I am creating with javascript that when I select the like button it prints Hi. I don't understand why when inspecting it is not selecting the button. I don't understand what I'm doing wrong. Can it be that I do not get the javascript url? index.hmtl <script src="{% static 'network/index.js' %}"></script> <form method="post">{%csrf_token%} <button onclick="darLike()">Like</button> <a id="resultado"></a> <svg xmlns="http://www.w3.org/2000/svg" width="16 " height="16 " fill="currentColor " class="bi bi-heart " viewBox="0 0 16 16 "> <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z "/> </svg> </form> index.js document.addEventListener('DOMContentLoaded', function() { document.addEventListener('click', () => function darLike() { const contenido = document.querySelector('#resultado') fetch(`like/${post.id}`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken } }) // Put response into json form .then(response => response.json()) .then(data => { console.log(data); contenido.innerHTML = "Hi" }) // Catch any errors and log them to the console .catch(error => { console.log('Error:', error); }); }); // Prevent default submission return false; }) -
How to dynamically submit form input values with OnChange event using JQuery in django
I'm currently developing a simple true odd finder calculator using python, django and jquery. I need to have form input submit actions executed by jQuery as the user types in the input values. The goal is to get rid of submit buttons in the frontend html. As of nowadays calculator based web applications don't require submit buttons. The functionality behavior should look like here. I did a research and found out that i need to use JQuery. After implementing the functionality in my app, am able to type the first form input element, however upon clicking the second form input so as to start typing, my application crashes with server error 500, if i go back then type the second form input, it updates output. How can i implement form input onChange using jquery to match the referenced functionality above. My template and JQuery code {% extends "base.html" %} {% block title %}Two Way True Odd Finder{% endblock %} {% block content %} <script type="text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('.form-control').change(function () { $('#myform').submit(); }); }); </script> <div class="container m-5"> <a href="{% url 'dashboard' %}" class="btn btn-primary">Dashboard Home</a> <a href="{% url 'index' %}" class="btn btn-primary">3 Way True … -
How to add secondary y axe in a graph object with Plotly?
I'm new with Plotly and I would like to add a secondary y axis to a Line graph in my Django view, how can I do that ? class AccountDetailView(SingleTableMixin, generic.DetailView): data_assets_hist = [] data_assets_hist.append(go.Line(x=x, y=get_test(), name='Test')) data_assets_hist.append(go.Line(x=x, y=get_bench(), name='Benchmark')) layout_weights = { 'yaxis_title': 'Title y axis', 'height': 520, 'width': 1100 } plot_div_1 = plot({'data': data_assets_hist, 'layout': layout_weights}, output_type='div',) context['plot_div_1'] = plot_div_1 return context From what I understand of the documentation the recommended way to add a secondary y axis is to call update_yaxes() but in my case it's not possible because I don't create a figure with make_subplots. I tried to insert the secondary_y parameter in several places but it throws an error. Invalid property specified for object of type plotly.graph_objs.Layout: 'secondary' -
Make fixtures for the standard Django's apps
I need to make the fixtures for the redirect app. For site I use: python3 manage.py dumpdata sites --indent 2 > fixtures/sites.json So I tried to use the code below to make the fixtures for redirect: python3 manage.py dumpdata redirect --indent 2 > fixtures/redirect.json But I see the error below: CommandError: No installed app with label 'redirect'. I need to make the fixtures for all standard app, like migrations and the others in the image below. -
Counting number of rows in the table of mysql database and printing in django webapplication
I have successfully connected Django forms with backend (MySQL) , now I have to count the rows in the table created and print its output in an HTML webpage of my Django web application. How can I do it? -
django.db.utils.DatabaseError how to fix it
I am new to django, I have created a project and apps and I would like to connect my project to the mongodb. when I enter python manage.py migrate command , I am getting below mentioned error. Terminal Output: Operations to perform: Apply all migrations: HomePage, YouTube, admin, auth, contenttypes, forum, sessions, star_ratings Running migrations: Applying star_ratings.0004_auto_20220420_1458...Not implemented alter command for SQL ALTER TABLE "star_ratings_rating" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "star_ratings_rating" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/django/db/backends/utils.py", … -
Ajax can not get data from Django view
I have a request to use Ajax to get data from Django views. This project was generated through cookiecutter Here is my code: config/urls.py: # API URLS urlpatterns += [ # API base url path("api/", include("config.api_router")),] ./config/api_router.py: from django.conf import settings from django.urls import path from rest_framework.routers import DefaultRouter, SimpleRouter from project.users.api.views import UserViewSet from app import views if settings.DEBUG: router = DefaultRouter() else: router = SimpleRouter() router.register("users", UserViewSet) app_name = "api" urlpatterns = router.urls urlpatterns += [ path("chart-data", views.chart_data), ] app/views.py: from django.shortcuts import render from django.http import JsonResponse def chart_data(request): return render(request, 'pages/home.html') def click(request): data_for_ajax = { 'a': {1: 1, 2: 2}, 'b': {3: 3}, 'c': {4: 4, 5: 5} } return JsonResponse(data_for_ajax) project/templates/pages/home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script defer src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script> function click() { $.ajax({ type: "GET", url: "api/chart-data", success: function(data) { console.log(data); } }) </script> </head> <body> <button onclick="click()">Click me</button> </body> When I accessed http://localhost:8000/api/chart-data and clicked the "Click me button", there is nothing in the console, and there is no error. -
How to enable autocomplete for Django HTML files in Pycharm?
I would appreciate some help with getting my Django HTML files color coded correctly. Currently none of the variables or tags are recognized by Pycharm. However, within the same file the basic html syntax is recognized (autocomplete and color coded): [snipped of Pycharm code1 I have tried to add Django in: Setting > Color Scheme Settings > Languages & Frameworks But it does not seem to show as an option. It is quite cumbersome to have to write each variable and tag manually. Thanks in advance. -
How to loop something to send in one email in Django
I like to send email to myself that contains the name of users who matches the criteria. My problem is that if I use the for loop in the mass_mail it sends every results in separated emails. So if I have 6 results it sends the email 6 times containing one results in every emails: (I am using the mass_mail because in the future I like to send emails to more users not just me.) user_weekly.py from django.core.management.base import BaseCommand from xy.models import Profile from django.core.mail import send_mass_mail recipient_list = Profile.objects.raw('SELECT * FROM auth_user LEFT JOIN xy_profile ON auth_user.id = xy_profile.user_id WHERE email = 1') messages = [(subject, 'Hello! Users are the following:' + r.last_name, from_email, ['my@email.com]) for r in recipient_list] send_mass_mail(messages) How can I reach that to send all the results in one email and not 6 separate emails in this case? I also tried that to make a variable like this: reclist = r.last_name but in this case it sends only one email with only one user's name. What should I do to get all the user's names in one email? -
model_type in Django template
I am learning Django from a book called Web Development with Django. In one of the activities there is a tag in one of the templates as below: {% block title %} {% if instance %} Editing {{ model_type }} {{ instance }} {% else %} New {{ model_type }} {% endif %} {% endblock %} what is the model_type? I have never seen this tag before. It is not in any of the view.py functions or anywhere else. Thank you -
How do I configure ORM if I want to reference foreign keys for a particular column?
class Member(models.Model): user_Id = models.CharField(max_length=50, primary_key=True) user_Nick = models.CharField(max_length=10, unique=True) user_Name = models.CharField(max_length=10) user_Driver = models.IntegerField() user_Phone = models.CharField(max_length=30, unique=True) user_Points = models.IntegerField(default=0) user_Email = models.CharField(max_length=50, unique=True) def __str__(self): return self.user_Id class Meta: db_table = 'TB_MEMBER' class LogPoint(models.Model): pot_Id = models.ForeignKey( "Member", related_name="MemberId", on_delete=models.CASCADE, db_column="pot_Id" ) pot_Amount = models.ForeignKey( "Member", related_name="MemberAmount", on_delete=models.CASCADE, db_column="pot_Amount" ) pot_date = models.DateTimeField(auto_now_add=True) pot_Reason = models.CharField(max_length=20) pot_Change = models.IntegerField() def __str__(self): return self.pot_Id class Meta: db_table = 'TB_LOGPOINT' I want to refer to the attribute user_Points in the User model as Foreign Key. I've done migration, but I don't think it's properly referenced because the data type becomes varcar, not integer. How do I configure ORM if I want to reference foreign keys for a particular column? -
Django ORM returns non-iterable object
Code Screenshot WeeklyStrMst.objects.filter(StoreId__in=stores).values() Here stores is of list datatype containing 6000-30000 values which are non-null, integer, so when I execute this, it returns me - <django.db.models.query.QuerySet object at 0x0000024FD4EAAAF0> I have tested with less than 2000 values it works fine. What could be possible reason and workaround for this scenario? How to pass a large list of array as a filter criteria? -
How to find db records valid from a certain date
Requirement I have a project where I want to store a list of prices for a given product, which are supposed to be valid after a certain date. The 'current_price' should show up on the Product list admin page (depending on the date of request) Problem My current implementation leads to excessive database queries Example product prices over time Product valid from Price 1 2022-03-01 100 EUR 1 2022-04-01 120 EUR 1 2022-05-01 130 EUR 2 2022-03-01 30 EUR 2 2022-04-01 40 EUR 2 2022-05-01 50 EUR expected result e.g. on 2022-03-15 PRODUCT CODE NAME CURRENT PRICE 2 Second product 30.00 1 First Product 100.00 e.g. on 2022-04-30 PRODUCT CODE NAME CURRENT PRICE 2 Second product 40.00 1 First Product 120.00 Code (working) I get the desired results when using the following code: models.py from django.db import models class Product(models.Model): product_code = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class ProductPrice(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices') valid_from = models.DateField() price = models.DecimalField(max_digits=8, decimal_places=2) class Meta: get_latest_by = 'valid_from' admin.py from django.contrib import admin from . import models import datetime @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): list_display= ['product_code','name', 'current_price'] def current_price(self,product): current_date = datetime.datetime.now() return product.prices.filter(valid_from__lte=current_date).latest().price def get_queryset(self, request): return super().get_queryset(request).prefetch_related('prices') … -
Moving data from a table sqlite to a new one in django
How can I move data from a sqlite tabla to another one using django? I need to do this because I want to use the table after for training a NN. -
Validation for UserCreationForm not working Django
Everything seems to be working fine, but if the form doesn't validate, instead of getting HTML validation errors, I get ValueError ar /register/: The user.register didn't return an HTTPResponse. It returned none instead. My code: if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Acount created!') else: form = UserCreationForm(): return render(request, 'users/register.html', {"form":form}) -
Django [TemplateDoesNotExist]
I am getting an error message when running server for making a django login faeture and cannot figure out why I am getting this error.. help is appreciated vs code log django error -
how to make a category of product visible in menu in all pages in django
html inside layouts and i make extends in other pages, all work fine but category menu (come from database) is hidden in some pages and i can see it just in one pages there is my code : def produit_list(request): produits = Produits.objects.all() categories = Category.objects.all() context = { 'produits':produits, 'categories':categories, } return render(request, 'shop.html', context) #categories.html <div class="col-md-4 pt-5"> <h2 class="h2 text-light border-bottom pb-3 border-light">Categories</h2> <ul class="list-unstyled text-light footer-link-list"> {% for cat in categories %} <li><a class="text-decoration-none" href="#">{{cat.name}}</a></li> {% endfor %} </ul> </div> i include this code inside base.html i want know how to load it in all website like menu in bottom of every page, now i can see it just in shop.html. Thank you -
How to restrict non-superuser users to delete with Django CBV?
I am using a function based view that restricts any users except the superuser to delete something and route the user to the same page site-list regardless if user is restricted or not. It is perfectly working. Here that working code: @login_required def delete_site(request, pk): site = TargetSite.objects.filter(primary_key=pk).first() if request.method == 'POST' and request.user.is_superuser: site.delete() messages.success(request, f'Successfully deleted "{site.site_name}" ', extra_tags='check') return redirect('site-list', project=site.project) else: messages.warning(request, f'Sorry, you\'re not authorized to execute this request', extra_tags='exclamation') return redirect('site-list', project=site.project) However, when I tried the CBV, it does not work same as the function based. The non-superuser is able to delete and not restricted: class SiteDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = TargetSite def test_func(self): site = self.get_object() if not self.request.user.is_superuser: messages.warning(self.request, f'Sorry, you\'re not authorized to execute this request', extra_tags='exclamation') return reverse('site-list', kwargs={'project': site.project}) return True def get_success_url(self): messages.success(self.request, f'Successfully deleted "{ self.object.site_name}" ', extra_tags='check') return reverse('site-list', kwargs={'project': self.object.project}) I also tried this one with test_func(self), but it just threw a 403 Forbidden message and does not route the user to the same site-list page. I believe I'm missing something. Can you please help? def test_func(self): if self.request.user.is_superuser: return True return False