Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Static Htmpl pages containing Tables and Plots from csv files in Python
I have a generic question here. Not a related code or trouble shooting issue. I will have csv files which I will have as data tables with multiple columns. I am looking to generate different group statistics (from different columns) and plots among the data columns. What I want is to create html files for the plots and the tables ( all in a static format) and host them to a private website ( which is of my choice ). What is the best platform to do that in python? I am seeing many different options when I search ( flask/django/react in python ) and shiny in R etc but not understanding what to do. The object is to have html files and put it to a website with tabs etc ( for multiple html files) How to do that? -
Changing attributes in Django Login Form
I am following a tutorial for Login in Django and after finishing I found that the Login Form requires the USername and Password but I want to replace the username with the user's Email instead. Here is the views.py @login_required def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Here is the forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] Here is the template <form style="padding: 30px 38px 27px 38px;" class="login100-form validate-form" method="POST"> <span class="login100-form-title p-b-34"> Account Login </span> <fieldset class="input100 m-b-20"> {% csrf_token %} {{ form|crispy }} … -
ValueError -- Django search form: Multiple select field with foreign key
I would like a search form for a model which results in a table with filtered view. Started out using django-tables2 and django-filter to achieve this. It all works fine. However, when I try to change a select field for a foreign key into a multiple select field, then I start running into issues. E.g., ValueError: Cannot assign "<QuerySet []>": "Test.library" must be a "Library" instance. ValueError: Cannot assign "<QuerySet [<Library: my lib!>, <Library: hmm>, <Library: a's lib>]>": "Test.library" must be a "Library" instance. Any tips? With the form, table, and filter, it's all a little confusing. # models.py class Library(models.Model): some_title = models.charField() class AbstractTest(models.Model): some_value = models.charField() library = models.ForeignKey( 'Library', on_delete=models.CASCADE) class Test(AbstractTest): another_value = models.charField() # forms.py class TestSearchForm(forms.ModelForm): # library should display as a muliple select field # do it here? library = forms.ModelMultipleChoiceField( queryset = Library.objects.all(), to_field_name = "title", required = False ) class Meta: model = Test widgets = { # library should display as a muliple select field # do it here? 'library': forms.SelectMultiple(), } # filters.py class SpectraFilter(django_filters.FilterSet): # library should be a multiple select filter library = django_filters.ModelMultipleChoiceFilter( queryset = Library.objects.all(), to_field_name = "some_title", required = False ) class Meta: … -
Any good folder structure for Component?
Scenario Most of projects nowadays using component to avoid duplicate code over the frontend. Because of this, normally in a project, there a tons of components. It was super confusing. Question How to properly manage all these components? Using naming convention or divide into different folder? Any clue? Is there any standard solution for these? -
Django form only sending GET requests
I have this add page which uses a django form to get information which i am trying to store within "tasks" list and display in the todo html page. i believe all my syntax is correct but it is not displaying the list of tasks when I submit the form. on cmd it detects a GET request every time i submit the form, shouldnt it be saying post? views: from django.shortcuts import render from django import forms tasks = [] class newTaskForm(forms.Form): task = forms.CharField(label="new task") # Create your views here. def index(request): return render(request, "tasks/todo.html", { "tasks": tasks }) def add(request): if request.method == "POST": form = newTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] tasks.append(task) else: return render(request, "tasks/add.html", { "form": form }) return render(request, "tasks/add.html", { "form": newTaskForm }) add: {% extends "tasks/layout.html" %} {% block body %} <form action="{% url 'tasks:add' %}"> {% csrf_token %} {{ form }} <input type="submit"> </form> <a href="{% url 'tasks:home' %}">Veiw list</a> {% endblock %} todo: {% extends "tasks/layout.html" %} {% block body %} <h1> To Do List</h1> <ul> {% for task in tasks %} <li> {{ task }}</li> {% endfor %} </ul> <a href="{% url 'tasks:add' %}">Add items</a> {% endblock %} -
Figuring out JSON memory leaks in Django
I am using Python 3 and Django 3.1.4 for a web application hosted on Heroku. I started experiencing R14 and R15 errors related to memory quota exceeding. The application involves a lot of API calls with large JSON data being sent to the client side via JSONResponse I followed some online resources to run tracemalloc for some of the views. tracemalloc.start() # ... run your application ... snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') print("[ Top 10 ]") for stat in top_stats[:10]: print(stat) I refreshed the page and I found this pattern. Iteration 3: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=290 MiB, count=3399976, average=89 B Iteration 4: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=406 MiB, count=4759963, average=89 B Iteration 5: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=522 MiB, count=6119933, average=89 B Iteration 6: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=638 MiB, count=7479913, average=89 B With each iteration, the size increases. It even goes beyond 1000 MiB. Can it be concluded that there is a memory leak with the way JSON data is being handled? How can I fix this problem? -
Python check multiple Unique columns when using POST method(RestAPI)
Pretend that I have multiple unique columns in my database. username = models.CharField(max_length=64, unique=True) email = models.CharField(max_length=64, unique=True) phone_number = models.CharField(max_length=64, unique=True) serial_number = models.CharField(max_length=64, unique=True) When I use POST method, I will use 4 queries to check each of these field exist in database.(If not then I will POST them in database) I am wondering is there a smarter way to check all multiple unique in the database? -
nginx throws bad request 400 when accessed through ddns domain
Working perfect when accessed through local web server IP but throws 400 error when accessed through NOIP hostname. For context, router is configured to forward requests to the web server on that port. This is the nginx config file: server { listen 80; server_name 192.168.1.64; #server_name example.ddns.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/projectdir; } location / { include proxy_params; # proxy_pass http://example.ddns.net; proxy_pass http://unix:/run/gunicorn.sock; } } I tried adding the lines where the hashtags are but to no avail. -
Django best practices
I am wondering if I am doing the right thing on my project organisation: For now each app has its template folder containing html files. Also each app has its own static file containing JS files and CSS files (one per html), is it what we do, "in best practices" 1html=1css? Then I also have common stuff, for example navbar, or footer html in a main folder located at the root of my project. I have seen several practices, but I am not able to tell which one is better. Thank you -
Django round in subquery
hi i am getting the progress percentage of each project in a ListView with subquery with the following code class projects(LoginRequiredMixin, ListView): model = Project template_name = 'project_list.html' ordering = ['project_title'] paginate_by = 10 queryset = Project.objects.annotate( todo_done=Count('todo', filter=Q(todo__state=True)) * 100 / Count('todo'), todo_left=Count('todo', filter=Q(todo__state=False)) * 100 / Count('todo'), ) in a project I have 12 tasks, 8 finished and 4 in progress. The system returns 66% completed and 33% in progress, whose sum is 99% and not 100% {{ project.todo_done }} {{ project.todo_left }} part of the bar is blank because the 1% is missing. I try to use round as follows but it is not possible todo_done=round(Count('todo', filter=Q(todo__state=True)) * 100 / Count('todo')), TypeError: type CombinedExpression doesn't define __round__ method -
Running Django app with docker-compose - applying migrations causes db to stop responding to queries but no errors are raised
I searched for this, and it seems like every post has some sort of related error message, but I get no error messages for this problem. It took me a while to even realize what was going on, but I still don't understand why. Essentially, I am trying to containerize my Django app with Docker. I am able to interact with the app on localhost:8000, and if I try my app's search function (the only functionality I've built out so far) before I apply migrations, I get an error as expected because certain tables don't exist. I can see in the logs the database is trying to search for the input from the web app. Once I apply migrations with docker-compose exec web python manage.py migrate --noinput, and I search for any term, I get no results back at all and no errors, and there's nothing in the database logs to suggest it's handling the query. I do see in the logs for the web container that it's noticing I am typing in search terms and pressing enter. On the frontend, I just see "0 results for [search term]", which is what should be returned if the db can't find … -
django-rules permissions not propagating as expected through Django REST Framework
I am trying to set up some basic authorization in my test app contact in a Django project using django-rules. There are two models, contact and address. I want to restrict deletion of objects based on my custom predicate is_owner. Here are my predicate and rules definitions in myapp/rules.py: import rules from shared.decorators import log_exec logger = logging.getLogger("myproject.auth") @log_exec(logger) @rules.predicate def is_owner(user, obj): if obj: if obj.created_by == user: logger.info("[OK] Permission granted.") return True else: logger.info("[NO] Permission not granted.") return False else: logger.info("No object defined.") return False # Rule definitions rules.add_perm("contact", rules.always_allow) rules.add_perm("contact.view_contact", rules.is_authenticated) rules.add_perm("contact.add_contact", rules.is_staff) rules.add_perm("contact.change_contact", rules.is_staff) rules.add_perm("contact.delete_contact", is_owner) rules.add_perm("contact.view_address", rules.is_authenticated) rules.add_perm("contact.add_address", rules.is_staff) rules.add_perm("contact.change_address", rules.is_staff) rules.add_perm("contact.delete_address", is_owner) I am checking the rules in two places: 1. Django shell This appears to work fine. Checking my users against the permission sets using has_perm appears to yield only expected results. 2. Django REST Framework When I make requests via my API I set up with Django REST Framework, I observe the following on deletion: Permission appears to be granted as expected (based on logging). However, the API returns 403 - unauthorized. Where should/could I check what changes between the rule validationand the response generation for the API? Is there a good … -
Display HTML content from Django
Whenever I receive an IPN in this url: https://www.example.com/payment/notifications, I want to display with JavaScript some HTML content to https://www.example.com/stream/notifications/<token>. The goal is to display some successful donation message to a streamer whose token is user.stream_token. Then he can take that url and configure the alert with OBS. This token is unique to every "streamer" and I can access it by doing user.stream_token I manage the IPN from the server like this: @csrf_exempt def notifications(request): jrequest = json.loads(request.body) if request.method == "POST": if jrequest['action'] == 'payment.created': # some code return HttpResponse(status=200) I want to run the JS function that displays the html content inside that block of code, because that's when I can confirm that a payment or donation has been approved. I know that Django is server-side and JS is client-side so I cannot just run a JS function inside there. Any ideas on how could I implement this in the simplest way possible? I read about WebSockets but the implementation is way too difficult for me to understand. -
how can you make an API change its data?
I have a quick question. This is the code I have, when it is clicked it should detect the URL inputted in a form, and then it runs a scrapper that prints out the emails found on the URL. I want the results to be printed on the same page. How should I make my API to achieve this? Javascript code: function submitURL() { const url = document.querySelector("#InputSearch").value; const data = { url }; fetch('http://127.0.0.1:8000/api/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); } Current API created (I want this to take the data of the emails found): class apiOverview(APIView): serializer_class = serializers.EmailsSerializer def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): url = serializer.validated_data.get('url') message = f'The url is {url}' return Response({'message': message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def patch(self, request, pk=None): return Response({'method': 'PATCH'}) def put(self, request, pk=None): return Response({'method': 'PUT'}) def delete(self, request, pk=None): return Response({'method': 'DELETE'}) -
how to change status value depends on email id in django?
how to change status values i amnot understanding please any one help in this senerio only its not changing his value all user i don't how to do please help ....how to change status values i amnot understanding please any one help in this senerio only its not changing his value all user i don't how to do please help .... i amnot understanding how to change status value if some one user logging first time his started session he will create his profile starting position he will keep status verifying again he will sending some link to register second person again he will logging he will create his registration after he will login he will create his profile then then first user status should be show pending second person status should be verify again second he will send some link to third person then third person login and he will create his profile then i want first person it should be completed second person pending and in third person profile it will show verifying … but in my case showing verifying all users whatever trade reference is their i passing three email ids they will get link in if … -
Amazon Pay integration with Django
Do you know how to integrate Amazon Pay with a Django Application? I've tried using the Amazon pay documentation but I couldn't. -
Searching Cards using Javascript by exclusion
I am trying to implement seach using Javascript by search cards using card-title and if it is not found in a card to be deleted from the html result. I had it working before in another but now when I was trying to implement it again it is not working for some reason. Here is the card html <main> <div class="container"> <div class="row"> <div class="col-md-12"> <form action="/store/s/" role="search"> <input name="q" id="search_here" class="mt-2 mb-2 form-control" placeholder="Type to search..."> </form> <section class="text-center mb-3"> <div id="box" class="row wow fadeIn"> {% for item in object_list %} <div class="col-lg-4 col-md-6 mb-3 outers"> <div class="card h-100"> <div class="view overlay"> <a href="{{item.get_absolute_url}}"> <img src="{{ item.image.url }}" class="card-img-top" alt=""> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body text-center mirror-face"> <a href="{{item.get_absolute_url}}" class="grey-text"> <h4 class="card-title proj-title">{{ item.title|capfirst }}</h4> </a> </div> </div> </div> {% endfor %} </div> </section> </div> </div> </div> </main> Here is the script <script> const input = document.getElementById('search_here') input.addEventListener('keyup', (e) => { var inputs = e.target.value.toLowerCase(); //do lowercase //loop through outer div and hide it document.querySelectorAll('.outers').forEach(function(el) { el.style.display = 'none'; }); //loop through outer ->card-title document.querySelectorAll('.outers .card-title').forEach(function(el) { //compare if (el.textContent.toLowerCase().indexOf(inputs) > -1) { el.closest('.outers').style.display = "block"; //if match show that div } }) }) </script> My question: … -
gunicorn fails to start: ModuleNotFoundError: No module named 'django'
I am using Django 3.1 with gunicorn (latest version). I have installed everything correctly as per the instructions here However when I run the command gunicorn --bind 0.0.0.0 foo.bar.wsgi, I get the following error stack trace: me@YOURBOX:/opt/websites/demo_project$ gunicorn --bind 0.0.0.0 foo.bar.wsgi [2021-01-16 22:11:09 +0000] [2737] [INFO] Starting gunicorn 20.0.4 [2021-01-16 22:11:09 +0000] [2737] [INFO] Listening at: http://0.0.0.0:8000 (2737) [2021-01-16 22:11:09 +0000] [2737] [INFO] Using worker: sync [2021-01-16 22:11:09 +0000] [2740] [INFO] Booting worker with pid: 2740 [2021-01-16 22:11:09 +0000] [2740] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 144, in load_wsgi File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 383, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/opt/websites/demo_project/foo/bar/wsgi.py", line 12, … -
reverse foreignkey modelform
models.py: class Team(models.Model): name = models.CharField(max_length=100, unique = True) class Member(models.Model): name = models.CharField(max_length=100, unique = True) team = models.ForeignKey(Team, on_delete = models.RESTRICTED, null = True) (One Member can be only part of one Team, but Team can have 0, one or any number of members) class MemberForm(forms.ModelForm): class Meta: model = Member Works as expected, but I want to make TeamForm: class TeamForm(forms.ModelForm): class Meta: model = Team fields = ['name', ' member__team'] but it doesn't work (there's no member__team field) I imagine form with multiplechoiceField - you can select from members which are connected with no team... I made own forms.Form: class TeamForm(forms.Form): name = forms.CharField(label = "Name", max_length=100, widget=forms.TextInput(), required = True) team_members = forms.MultipleChoiceField(choices=Member.objects.filter(team__isnull=True).values_list('id','name')) But has problem with updating: views.py: if form.is_valid(): team = Team.objects.create(name = form.cleaned_data['name']) #and now update all members in form.cleaned_data['team_members'] with team= team # but how? -
Pandas TypeError: cannot subtract DatetimeArray from ndarray
I ran into a really annoying error and I've been stuck for a while. I have two Pandas time series which look like this: 338 2019-09-06 339 2019-08-13 340 2019-07-26 341 2019-07-25 342 2019-07-10 Name: Target announced, Length: 343, dtype: datetime64[ns] and : 338 2018-08-16 339 2018-11-16 340 2017-06-02 341 2017-07-27 342 2019-03-28 Name: IPO date, Length: 343, dtype: datetime64[ns] All I'm trying to do is to subtract the second one from the first one. When I do this in Jupyter Notebook it works fine, but when I transfer the code to PyCharm I get the following error: TypeError: cannot subtract DatetimeArray from ndarray I tried to install the same pandas and numpy versions in my virtual environment as the ones I use in Jupyter Notebook. Nothing helps. Everything I do has to do with TimeSeries and not being able to manipulate those in PyCharm is killing my project. I'd appreciate your help! -
`op_name` parameter for `graphene_django`
The django graphene documentation shows a test example like this: class MyFancyTestCase(GraphQLTestCase): def test_some_query(self): response = self.query( ''' query { myModel { id name } } ''', op_name='myModel' ) content = json.loads(response.content) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like ... They don't have any API documentation for what op_name is, and what we should set it as. I tried to set it to my query name, but get the error: [{'message': 'Unknown operation named "myQuery".'}] -
Force_authenticate superuser django rest unit testing
I have structured my api so that only the superuser can delete accounts. I am trying to force authenticate a superuser in my unit test but I am running into issues. Unit test: class PrivateUserApiTests(TestCase): """Test the users API (private)""" def setUp(self): self.user = create_user( email='tes111t@test.com', password='test123', name='name', ) self.user.is_superuser = True self.client = APIClient() self.client.force_authenticate(user=self.user) def test_user_successful_delete(self): """Test that user was succesfully deleted""" payload = {'email': 'test@test123.com', 'password': 'test123'} user = create_user(**payload) res = self.client.delete(reverse('user:delete_user', kwargs={'pk': user.id})) self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) ERROR: Traceback (most recent call last): File "/app/user/tests/test_user_api.py", line 152, in test_user_successful_delete self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) AssertionError: 403 != 204 Am I using the force_authenticate() method wrong? How can I create a user that is a superuser -
How to create service for django app with nssm on windows
nssm service to run django application. I have created nssm service to run my django app on windows machine but it doesn't work. Please suggest an alternative package or the right config to get the service running. Here is the command I used. Adding nssm to environment variable some_shell>setx PATH "%PATH%;C:\Users\app\nssm" /M Creating nssm service some_shell>nssm install myappservice Here I gave C:\Users\django_app\manage.py as path and; C:\Users\django_app as Startup directory I get "windows could not start the myappservice on local computer..." error whenever I try to start the service. -
Creating messaging (chatting) functions in Django
I created models for messaging between users of my project. My messaging models: class Chat(models.Model): id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32) chat_participants = models.ManyToManyField(User, blank=True) class Meta: db_table = 'chat' verbose_name_plural = 'chats' class Message(models.Model): id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(_('text'), max_length=1500, null=True, blank=True) send_datetime = models.DateTimeField(auto_now_add=True, blank=True) class Meta: db_table = 'message' verbose_name_plural = 'messages' class MessageRecipient(models.Model): id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32) message = models.ForeignKey(Message, on_delete=models.CASCADE) recipient = models.ForeignKey(User, on_delete=models.CASCADE) is_seen = models.BooleanField(_('is_seen'), default=False) class Meta: db_table = 'message_recipient' verbose_name_plural = 'message recipients' unique_together = ('message', 'recipient') How can I automatically align 'author' field in Message class (model) to the ID of user who writes a message? Now I need by myself choose the 'author' from the (not real) users that are in my database, but it is wrong, it has to be automatically selected depending on who writes the message. Or, let's, say who's account this message is being written from. In MessageRecipient class (model) I have to choose recipient myself, and I can choose not only from the participants of the particular chat group where the message has to be arrived, but … -
Creating Delete User Unit Test Django rest_framework
I'm struggling to figure how to get the id of the user I created using the create_user() function in my unit test. Unit test below: from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status DELETE_URL = reverse('user:delete_user') class PrivateUserApiTests(TestCase): """Test the users API (private)""" def setUp(self): self.user = create_user( email='tes111t@test.com', password='test123', name='name' ) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_user_successful_delete(self): """Test that user was succesfully deleted""" payload = {'email': 'test@test123.com', 'password': 'test123'} create_user(**payload) # Here is where I create the user I want to delete user = get_user_model().objects.get() res = self.client.delete(DELETE_URL) # I'm not sure how to pass the id of the user I just created. The way my url works is: (the id passed in is the user that is deleted) 0.0.0.0:8000/api/user/delete-user/id urls.py urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), path('all_users/', views.RetrieveUsersView.as_view(), name='all_users'), path('delete-user/<int:pk>', views.DeleteUserAPI.as_view(), name='delete_user') ] When using the self.client.delete() How do i pass in the id?