Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: decode() got an unexpected keyword argument 'verify' djangorestframework simple jwt
I'm using djoser for authentication and I'm getting TypeError: decode() got an unexpected keyword argument 'verify'. The /jwt/create/ endpoint is working and returning the access and refresh tokens but I can't verify or get the user's details (/auth/users/me/). The same code works in my previous project. Any idea what could be causing the error? {Traceback (most recent call last): File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 414, in initial self.perform_authentication(request) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 324, in perform_authentication request.user File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\request.py", line 227, in user self._authenticate() File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\authentication.py", line 40, in authenticate validated_token = self.get_validated_token(raw_token) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\authentication.py", line 94, in get_validated_token return AuthToken(raw_token) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\tokens.py", line 43, in init self.payload = token_backend.decode(token, verify=verify) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\backends.py", line 90, in decode return jwt.decode( TypeError: decode() got an … -
Creating months based on start date and end date value in django
I have been working on an application where user is required to create monthly tasks, so I made a model named AcademicYear and Months, now I want to take only the start_month and end_month input from user, and based upon the values of these fields, I want to create months automatically once the year object is create. class AcademicYear(SingleActiveModel, models.Model): title = models.CharField(max_length=10) start_month = models.DateField() end_month = models.DateField() def __str__(self): return str(self.title) class Months(models.Model): year = models.ForeignKey(AcademicYear, on_delete = models.PROTECT, related_name='year') months = models.CharField(max_length = 20) ??? what could be the logic or a solution which can be applied here? -
Please explain the proper configuration of jinja2 templating with django(3+). I am not getting clear view about this
I have configured the Django project with default DTL. But I want to use jinja2 templating with the Django project. I am not getting a clear point to configure it properly with Django. As I am new to development. Can someone please help me to understand this, and explain how to configure jinja2 with Django properly? -
select filter once added in the db
I need a filter for that select as you can see in the background there are green blocks with the names written in select, those blocks are associated with a board and then saved in the db. This box is a modal that I need to add a group within my tab, I would like them to disappear every time I add a new one in the db. example I create a box and in the select I put group 5. on click it refreshes the page with the added group 5 and if I had to reopen the modal in the select there must no longer be group5. form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] html {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">CREA</h1> <a href="{% url 'lista-gruppi' %}" class="btn btn-outline-primary">LISTA</a> </div> <hr> <div class="scheda mb-4"> <div class="d-flex justify-content-between align-items-center"> <h4 style="margin-bottom: 0;">Nome: {{ scheda.nome_scheda }}</h4> <div> <p style="margin-bottom: 0;"> <span><strong>Inizio: {{ scheda.data_inizio }}</strong></span> | <span><strong>Fine: {{ scheda.data_fine }}</strong></span> </p> </div> </div> </div> <div class="box"> {% for gruppo in scheda.gruppi_scheda.all %} <div … -
Send a list in POST requisition - Django Rest Framework
i trying send a list in a POST requisition in Django Rest Framework. My objective like this: Nested Relationship, but i want a list. What i need: { "id": 3435, "titulo": "Livro x", "editora": "Editora x", "foto": "https://i.imgur.com/imagem.jpg", "autores": ["Autor 1"] } What i am getting: { "autores": [ { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } ] } My serializers.py file: from rest_framework.serializers import ModelSerializer from .models import Autor, Livro class AutorSerializer(ModelSerializer): class Meta: model = Autor fields = ('nome') class LivroSerializer(ModelSerializer): autores = AutorSerializer(many=True) class Meta: model = Livro fields = ('id', 'titulo', 'editora', 'autores') def create_autores(self, autores, livro): for autor in autores: obj = Autor.objects.create(**autor) livro.autores.add(obj) def create(self, validated_data, **kwargs): autores = validated_data.pop('autores') livro = Livro.objects.create(**validated_data) self.create_autores(autores, livro) return livro Where i going wrong? -
Invalid data Expected a dictionary, but got ModelBase
{ "non_field_errors": [ "Invalid data. Expected a dictionary, but got ModelBase." ] } I get this error in postman when I try to upload a CSV File through Postman -
Many to many field reverse lookup with TreeQuerySet
I have made no leg way with my issue, I have tried following multiple tutorials but am getting no where. I have looked in these places (and elsewhere) - Django Model API reverse lookup of many to many relationship through intermediary table https://www.revsys.com/tidbits/tips-using-djangos-manytomanyfield/ https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ https://readthedocs.org/projects/django-mptt/downloads/pdf/latest/ class CategoryTree(MPTTModel): title = models.CharField(max_length=120, default="no name") slug = models.SlugField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') products = models.ManyToManyField(Product, blank=True) class MPTTMeta: order_insertion_by = ['title'] class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) is_digital = models.BooleanField(default=False) # User Library Lets say in the Product models I have an item with the title Iron Man Toy, I need to find a way of finding the category (or categories) it belongs to in the CategoryTree model. I had one solution which came close to solving my problems but if the item was in two seperate categories, then I got an error message. -
Nginx not finding static files in Dockered Django app in Azure Web App for containers
I managed to run my Django app locally with docker compose( Django container + Nginx container) and it works fine, but when i want to run it in Azure web app for containers nginx can't find the ressources. I don't know if i should change some configuration so it can work in Azure services or i need to enable ports in azure app settings therefore my containers could communicate. This is my nginx configuration (nginx.conf) : upstream myapp { server web:8000; } server { listen 80; server_name myappname.azurewebsites.net; location / { proxy_pass http://myapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/static/; } location /media/ { alias /home/app/web/media/; } } I don't know why it did work locally when i run docker compose but in azure web app nginx can't find static files. Please let me know if I need to clarify or include anything else. Thanks in advance. -
Why django channels are not receiving headers?
I am trying to code simple python websocket client that will communicate with django channels. I am using python websockets library to achieve that. After running the following function I expect the get custom headers in scopes['headers'] async def connect(self): async with websockets.connect( f'ws://{self.HOST}:{self.PORT}/{self.URL_PATH}/{self.ID}/', extra_headers=[ ('CUSTOM_HEADER_1', 'NyNLFijhMasdaasdssA21TST1aJL_zLDArCbr8o',), ('CUSTOM_HEADER_2', '0',), ('CUSTOM_HEADER_3', '21312312',), ('CUSTOM_HEADER_4', 'dasdsadwq',), ('CUSTOM_HEADER_5', 'dshaghdashdghasdgjhsgkagukILKDSLHFb') ] ) as ws: await ws.ping() Instead of my custom headers I receieve following headers in the scope [(b'host', b'localhost:8001'), (b'upgrade', b'websocket'), (b'connection', b'Upgrade'), (b'sec-websocket-key', b'9asdasdasjAc9ruOg=='), (b'sec-websocket-version', b'13'), (b'sec-websocket-extensions', b'permessage-deflate; server_max_window_bits=12; client_max_window_bits=12'), (b'user-agent', b'Python/3.8 websockets/10.0')] -
Google Calendar API authorization working on localhost but not on Heroku
I want to use the Google Calendar API for my Django application. I have followed the instructions here: https://karenapp.io/articles/how-to-automate-google-calendar-with-python-using-the-calendar-api/ I have also added the redirect uri's in Google API - seems like a browser tries to open up on the server side (as it does on local, but I am unable to manipulate it as the browser from the server side does not show up). Any ideas on what I can do? -
OIDC with Keycloak and Django - Missing States
I'm attempting to set up OIDC with Keycloak as my IdP and Django (using Django Rest Framework and mozilla-django-oidc) as my client server. I have got keycloak installed and a rough Django application stood up that successfully redirects to keycloak where I can then successfully authenticate (to keycloak), but when I'm redirected back to django I'm missing information, specifically oidc_states. The redirect to django triggers this log entry: [12/Oct/2021 08:28:06] "GET /api/oidc/callback/?state=QGsO26esqdtHZcsfRfYoXvUy0QWcGdZv&session_state=493887a4-600e-4dd2-aaaf-4134ea671c9a&code=dfe1573e-cf8e-4829-8874-a3500ba63712.493887a4-600e-4dd2-aaaf-4134ea671c9a.c1dfdb46-140c-4ccd-8308-6db3b468346a HTTP/1.1" 302 0 This contains three keys: state, session_state, and code. The default callback view provided by mozilla-django-oidc contains this: def get(self, request): """Callback handler for OIDC authorization code flow""" if request.GET.get('error'): if request.user.is_authenticated: auth.logout(request) assert not request.user.is_authenticated elif 'code' in request.GET and 'state' in request.GET: if 'oidc_states' not in request.session: return self.login_failure() # ... Because keycloak isn't making the redirect with oidc_states added, this is immediately failing and I haven't been able to figure out why. I'm guessing that the problem is with my keycloak client configuration? -
Dockerized django, permission denied
Hi I dockerized django and I have a problem, after computer restart I can not run my app because some "data/db" directory was added which throws an error - " Permission denied: '/home/maciej/djangoapp/fitshop/data/db'" It happens when I want to "runserver" or just git add . settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fituser', 'PASSWORD': 'fitpass', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yaml services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=fitshop - POSTGRES_USER=fituser - POSTGRES_PASSWORD=fitpass ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code restart: always ports: - "8000:8000" depends_on: - db -
Caching authentication result in django-rest-framework-jwt
I`m using Auth0 authentification in a webapp / django-server combination. Auth0 is not the fastest auth framework, it always takes 200ms to authenticate. My webapp sends a lot of requests to the django server, so I thought about caching the authentication for a few seconds. This improves the speed of my app a lot. Is this a good way? Do you see any disadvantages / security issues in doing it this way? django config: REST_FRAMEWORK = { (...) 'DEFAULT_AUTHENTICATION_CLASSES': ( (...) 'rg_auth.rest_framework_authentication_classes.RgJSONWebTokenAuthentication', (...) ), (...) } authentication class: import hashlib from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.authentication import get_authorization_header from django.core.cache import cache class RgJSONWebTokenAuthentication(JSONWebTokenAuthentication): def authenticate(self, request): # Get from cache cache_key = self._rg_get_cache_key(request) cached_user_payload_tuple = cache.get(cache_key) # Is cache set? if cached_user_payload_tuple: # Cache is set: Return user/payload tuple return cached_user_payload_tuple else: # Cache is not set: Authenticate and save tuple to cache for 10 seconds user_payload_tuple = super().authenticate(request) if user_payload_tuple: # Set cache cache.set(cache_key, user_payload_tuple, 10) # Return tuple return user_payload_tuple def _rg_get_cache_key(self, request): auth_header = get_authorization_header(request) auth_header_md5 = hashlib.md5(auth_header).hexdigest() return "RgJSONWebTokenAuthentication_{}".format(auth_header_md5) -
djnago project is not running on putty (digitalocean)
I trying to run my django project on putty (digital ocean). but when I am running this its not loading. getting error ERR_CONNECTION_TIMED_OUT I am not setting any environment variable. just trying to run project on IP address of putty this is my settings.py ALLOWED_HOSTS = [ '*',] Step 1 — Install Python and pip sudo apt-get update && sudo apt-get -y upgrade sudo apt-get install python3 sudo apt-get install -y python3-pip Step 2 — Install virtualenv pip3 install virtualenv Step 3 — Move to home cd /home mkdir Electronics cd Electronics Step 4— create virtual Environment and activate it virtualenv Unions . env/bin/activate it’s activated once the prefix is changed to (Unions) Step 5— Install Django pip install django Step 6 – Move our project outsite the Unions folder Step 7- sudo ufw allow 8000 Step 8— Move to project folder (Unions) root@localhost:/home/Electronics# cd Webproject/ Step 9—Run Project (Unions) root@localhost:/home/UnionElectronics/Webproject# python manage.py runserver ip_address:8000 I does this for run project on putty(digital ocean) ip. How can I run project on http://ip_address:8000/ -
Django Broken pipe
I opened the website I am currently working, in localhost with Django. The fonts, and layout has changed. The terminal displays broken pipe (don't know what it is). Font has changed and text has become bold. I restarted the server, but it was of no use. How can I fix this issue? The bootstrap navbar has changed, so has this paragraph What was the reason for this happening and how can I fix it? I have made no changes to the code and this just happened all of a sudden. Edit 1 : There are no database connections or any API calls -
Django save changes not reflecting on database
I know there are some similar posts, but nothing I've read could fix my issue. I have the following model: class Run(models.Model): id = models.AutoField(primary_key=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) description = models.TextField(blank=True, null=True) model = models.ForeignKey(Model, on_delete=models.CASCADE) script = models.ForeignKey(Script, on_delete=models.CASCADE) parameters = models.ForeignKey(Parameters, on_delete=models.CASCADE) weights = models.ForeignKey(Weights, on_delete=models.CASCADE, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) train_score = models.FloatField(blank=True, null=True) validation_score = models.FloatField(blank=True, null=True) and the following function: def save_run(run_id: str, model, train_score: float, validation_score: float): ... run: Run = Run.objects.get(id=run_id) run.train_score = train_score run.validation_score = validation_score run.save() but, even though it finds the run on the database, "saves successfully" and logs all attributes fine, even after saving it, the changes don't reflect on the database. I've tried forcing with update_fields=["train_score", "validation_score"] and force_update=True without success. Any ideas? -
receiver is not working in django signals
I've tried to implement django signal's m2m_changed from the documentation here https://docs.djangoproject.com/en/3.2/ref/signals/#django.db.models.signals.m2m_changed Whenever I add/remove new position from the admin panel, the total_price is supposed to change by using signal receiver. But the receiver is not responding at all. I am supposed to see the pre_save/post_save at the shell when a new position is added, and pre_delete/post_delete when a new position is removed as the value of the action. But in the shell absolutely nothing gets printed. Even not the string 'action' gets printed. So I understand that the receiver is not working. I can't seem to find the issue here. Kindly help me. my model is class Position(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.FloatField(blank=True) created = models.DateTimeField(blank=True) # overriding the default save method def save(self, *args, **kwargs): self.price = self.product.price * self.quantity return super().save(*args, **kwargs) def __str__(self): return f"id:{self.id}, product: {self.product.name}, quantity: {self.quantity}" class Sale(models.Model): transaction_id = models.CharField(max_length=12, blank=True) # In utils position = models.ManyToManyField(Position) total_price = models.FloatField(blank=True, null=True) #in signals salesman = models.ForeignKey(Profile, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"Sales amount: {self.total_price}円" # overriding the default save method def save(self, *args, **kwargs): if self.transaction_id == '': … -
Django annotate a list of aggregate methods
I have this qs = queryset\ .values(x=F('timestamp'))\ .annotate(min=Min('speed'), avg=Avg('speed'), max=Max('speed')) \ .order_by('-x') which results in <MotionQuerySet [{'x': 1632249000, 'min': 77, 'avg': 83.4, 'max': 96}, {'x': 1632162600, 'min': 61, 'avg': 83.6667, 'max': 114}, ...] Is there any way to make this output like <MotionQuerySet [{'x': 1632249000, 'y': [77, 83.4, 96}, {'x': 1632162600, 'y': [61, 83.6667, 114]}, ...] ? I can achieve it by iterating over each object of the returned queryset and creating a list of dictionary but I am looking for a better approach. -
How to change image field into file field in django?
I have a model with imagefield in it, is there any way to change that into filefield. Please also explain way to identify image while uploading. -
Wrong Python version running in Docker
No matter what I try, my Docker container is using Python 3.10 rather than what I need and specify, which is Python 3.7. How can I force Docker to use 3.7 for a specific image/container? I'm a novice Docker user and some of these Docker configuration files were not written by me, so forgive my ignorance. The Error Here's the error. You can clearly see that Docker is using Python 3.10. website_1 | Traceback (most recent call last): website_1 | File "/code/manage.py", line 10, in <module> website_1 | execute_from_command_line(sys.argv) website_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line website_1 | utility.execute() website_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 357, in execute website_1 | django.setup() website_1 | File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup website_1 | apps.populate(settings.INSTALLED_APPS) website_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 120, in populate website_1 | app_config.ready() website_1 | File "/code/website/apps.py", line 11, in ready website_1 | import website.signals website_1 | File "/code/website/signals.py", line 4, in <module> website_1 | from wand.image import Image, Color website_1 | File "/usr/local/lib/python3.10/site-packages/wand/image.py", line 3383, in <module> website_1 | class Iterator(Resource, collections.Iterator): website_1 | AttributeError: module 'collections' has no attribute 'Iterator' Docker configuration files My Dockerfile FROM python:3.7 # Setup some other prereqs needed: RUN apt-get update && apt-get … -
Can I use Django admin panel as the only view for the admin of the site not for developer?
I am creating an E-Learning system (similar to Udemy) where I have instructors, students and admins. I was thinking to create a panel for each one of these stakeholders. My question is, can I use Django's admin panel, where I need this panel to block users and block a course and so on? Thank you. -
l'utilisation d'un channels_layer dans un models django [closed]
hello I want to communicate my Notification class with my websocket so that I register a new instance of the notification object that I can retrieve a message via my websocket unfortunately my code does not work as I expected Class notification here my : class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.TextField(max_length=300) is_seen = models.BooleanField(default=False) def __str__(self): string = f'{self.user} ({self.notification}): {"False" if self.is_seen is False else"True"}' return string def save(self, force_insert=False, force_update=False, using=None, update_fields=None): channel_layer = get_channel_layer() notification_count = Notification.objects.filter(is_seen=False).count() data = {'count': notification_count, 'courrent_notification': self.notification} async_to_sync(channel_layer.group_send)( 'notification_groupe', { 'type': 'disconnect', 'value': json.dumps(data)}) super(Notification, self).save() my model consumer: class Notification_consumer(WebsocketConsumer): def connect(self): self.room_group_name = 'notification_groupe' self.room_name = 'notification_consumer' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.room_name ) self.accept() self.send(json.dumps({"status": "connected to notification consumer!"})) def receive(self, text_data=None, bytes_data=None): print(text_data) self.send(json.dumps({"status": "notification consumer a votre service"})) def send_notification(self, event): print('send_notification') print(event) print('send_notification') def disconnect(self, code): self.send(json.dumps({"status": "déconnexion effectuée!"})) print('déconnecxion') -
How can i load .tar and do predictions in django
I am building a web application to make predictions using PyTorch. I have trained a model and saved the model weights in the .tar file and now I want to load the model and do predictions in Django how can I do it. need help I am attaching my prediction code below def predicting(model, device, loader): model.eval() total_preds = torch.Tensor() total_labels = torch.Tensor() print('Make prediction for {} samples...'.format(len(loader.dataset))) with torch.no_grad(): for solute_graphs, solvent_graphs, solute_lens, solvent_lens in tqdm(loader): outputs, i_map = model( [solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device), torch.tensor(solvent_lens).to(device)]) total_preds = torch.cat((total_preds, outputs.cpu()), 0) # total_labels = torch.cat((total_labels, data.y.view(-1, 1).cpu()), 0) # return total_labels.numpy().flatten(),total_preds.numpy().flatten() return total_preds.numpy().flatten() -
Django docker-compose-prod isn't work correctly
I'm trying to prep a Django application for production. I created an alternate docker-compose YML file where I specify DEBUG=False. However when I run the Django check for deployment, it says that DEBUG is set to True. $ docker-compose down $ docker-compose -f docker-compose-prod.yml up -d --build $ docker-compose exec web python manage.py check --deploy but in local server it is worked(I mean the debug is Turn off) How can I fix it? -
How to use reverse with optional parameters in django?
I have the below URL in which I pass an integer value (pk) now when I am calling reverse on this URL I am getting the below-mentioned error. urls.py urlpatterns = [ path('batch-postpone/<int:pk>/', postpone_batch, name='batch-postpone'), ] tests.py class ABCTestCases(APITestCase, TestCase): self.postpone_batch_url = reverse('batch-postpone') Error that I am getting... django.urls.exceptions.NoReverseMatch: Reverse for 'batch-postpone' with no arguments not found. 1 pattern(s) tried: ['batch\\-postpone/(?P<pk>[0-9]+)/$']