Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Syncing Production values with Local
When I run my site on localhost it works using a Sql database now when I try to run it on production. It produces the following it seems to not have created the field receiverDeleted. ProgrammingError at / column pages_messages.receiverDeleted does not exist LINE 1: ...r_id" = 1 AND NOT "pages_messages"."read" AND NOT "pages_mes... ^ Request Method: GET Request URL: https://arundeepchohan.herokuapp.com/ Django Version: 3.2.9 Exception Type: ProgrammingError Exception Value: column pages_messages.receiverDeleted does not exist LINE 1: ...r_id" = 1 AND NOT "pages_messages"."read" AND NOT "pages_mes... ^ Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py, line 84, in _execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Thu, 03 Feb 2022 12:16:13 -0800 -
Django PostgreSQL ArrayField does not work
I have just switched to PostegreSQL. Now whenever I add the following code to my Custom User Model, the database is broken, no new values are added to the database, for example during registration from django.contrib.postgres.fields import ArrayField class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email'), unique=True) username = models.CharField(max_length=150, unique=True) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(default=timezone.now) code = models.ImageField(blank=True, upload_to='code',) #part that breaks the databse: ip_addresses = ArrayField( models.CharField(blank=True), default=list) From the moment also no more migrations are recognized. Or I get something like this django.db.utils.ProgrammingError: column "ip_addresses" does not exist LINE 1: ...ER COLUMN "ip_addresses" TYPE varchar(15)[] USING "ip_addres... What error I get is 50 50 chance but atleast the first error is always here. I also tried this which did not work either ip_addresses = ArrayField( models.CharField(max_length=15), default=list) -
What am I doing wrong with action url in my form
I am trying to do search method in my_app. Code in my navbar.html is as below. It is not full code. The other buttons in the navbar work fine. These are not forms - just regular links. <form class="d-flex" action="{% url 'search_record' %}" method="POST"> {% csrf_token %} <input class="form-control me-2" type="text" placeholder="Search"> <button class="btn btn-primary" type="button">Search</button> </form> In my urls.py I have name "search_record" urlpatterns = [ path('show/', show_record, name="show_record"), path('new/', new_record, name="new_record"), path('edit/<int:id>/', edit_record, name="edit_record"), path('del/<int:id>/', delete_record, name="delete_record"), path('search_record/', search_record, name="search_record")] I have the appropriate entries in the file views.py def search_record(request): return render(request, 'my_app/search_record.html', {}) And I also have a template file search_record.html in the directory templates/my_app whose content is as follows: {% extends 'my_app/index.html' %} {% block title %} Search Results {% endblock %} {% block page %} <h1>Results ...</h1> {% endblock %} When I am using the url: http://127.0.0.1:8000/my_app/search_record/ in the browser then search_record.html works good it shows me "Results ...", but clicking the Search button in the navbar does't work. After clicking this button, nothing happens. What am I doing wrong ? I have django 4 in my app. -
How do I parse a string in Django templates?
I am trying to have my django app display some text on the page. My string, coming in from the view, would be something along the lines of: 'Hello! This is my twitter @profile! send me an email at me@mail.com Now I want to be able to display the string as: 'Hello! This is my twitter @profile! send me an email at me@mail.com BUT @profile (without the '!') must be a link to https://twitter.com/profile If I make my logic in views and send as a string: Hello! This is my <a href="https://twitter.com/profile" target="_blank"> send me an eamil at me@mail.com The result will be to actually to see the tags, which I obviously don't. How do I fix this? considering that the strings coming in will be many and I display them via a python-enabled loop. Thanks! -
how to set Referer-Policy for static javascript files in Django
I have a static Javascript file in a django project that sends a request to another domain to render an iFrame which has my site listed in frame ancestors. At the moment I don't think the referer header is being set as Referer-Policy is set to 'same-origin'. I've tried setting this with SecurityMiddleware in Middleware: SECURE_REFERER_POLICY = 'strict-origin-when-cross-origin' How can I set this policy? Which is still no good, Referer-Policy header stays as 'same-origin' The file in question is connect-streams.js from here, which is used for embedding Amazon Conncet CCP within a website. https://github.com/amazon-connect/amazon-connect-streams/blob/master/Documentation.md All other settings within Connect and in the HTML are OK as it works in an S3 bucket. The Django app is deployed in a docker compose on EC2 with nginx and gunicorn, with correct SSL certificates. -
Django - Need helping writing annotated query
I'm trying to better understand how to write some more advanced queries. I'm used to the basic Model.objects.all() and .filter(), etc, but I'm having trouble writing out queries that are annotated. Here is my model setup (I have removed any additional fields that are not necessary for this question): from django.db import models class Client(models.Model): name = models.CharField(max_length=100) class Project(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) class Campaign(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="campaigns") class Advertisement(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='advertisements') What I need is a query that shows how many Advertisements each client has, ordered by most to least. I'm trying to follow the docs from here: https://docs.djangoproject.com/en/4.0/topics/db/aggregation/ but their annotation example isn't as nested, the publisher model example is a foreign key on the book object, where as with mine the client is a foreign key of a project, which is a foreign key of a campaign, which is a foreign key of advertisements. Any advice on how to drill down through the layers of the models to get the info I need? -
django: submit form and redirect to the new page
I need to render and redirect to the new page called CreateOrder.html at path: "homepage/order/", after user click the form submit button (i.e."Order Now button) in the home page. what is the correct way to update(render) the CreateOrder.html and redirect to this page) #views.py def CreateOrder(request): navi_load = request.session['navi_load'] navi_unload = request.session['navi_unload'] dist = request.session['dist'] charge = request.session['charge'] return render(request, 'OnlinePricing/CreateOrder.html', {'pickup_address': navi_load, 'delivery_address': navi_unload, 'distance': dist, 'charge': charge}) #urls.py urlpatterns = [ path('', views.OnlinePricing, name='OnlinePricing'), path('order/', views.CreateOrder, name='CreateOrder'), ] #home page HTML <form> ... <button type="submit">Get Price</button> <button type="submit" style="margin-left:10px;">Order Now</button> </form> #CreateOrder.html <html> <div> <label>pickup_address:</label> <span id="pickup_address"> {{ pickup_address }} </span> </div> <div> <label>delivery_address:</label> <span id="delivery_address"> {{ delivery_address }} </span> </div> <div> <label>dist:</label> <span id="distance"> {{ distance }} </span> </div> <div> <label>charge:</label> <span id="charge" style="color: #ff0000;font-size:25px"><b>{{ charge }}</b></span> </div> </html> -
ImportError: No module named pathlib Windows OS and Python version 3.8
Hi im trying to run a venv for my project. Everythin goes well install requirments and creating a my venv. The problem is that when i try to make a manage.py migrate i get this error. Ive looked everywhere and i got python version 3.8 installed. Pathlib is part of the package from python 3.4. I use Windows and python 3.8 with Django version 3.0.12- My project is based on a cockiecutter and i dont want to update to the latest version om django. Does anone know what the problem is and how it can be solved? manage.py migrate Traceback (most recent call last): File "E:\Dev\Fooders\fooders\manage.py", line 4, in <module> from pathlib import Path ImportError: No module named pathlib -
Django rest framework: how to override `is_valid` on a serializer created with `many=True`?
I have tried to override the create method on my viewset class in order to be able to create multiple instances of my model at once. The create method now has the following lines: def create(self, request, *args, **kwargs): ... print('Debug 0') serializer = self.get_serializer( data=request.data, many=True ) print('Debug 1') serializer.is_valid(raise_exception=True) print('Debug 2') self.perform_create(serializer) print('Debug 3') return Response(serializer.data) If I now try to override the is_valid method within the serializer class, I get surprising behavior. Suppose I now try to override the is_valid method within the serializer class with a simple wrapper: def is_valid(self, raise_exception=False): print('is_valid was called') return super(AlbumSerializer, self).is_valid(raise_exception) If there are no validation errors then I would expect the message "is_valid was called" to appear after after "Debug 1". To my surprise though, it appears after "Debug 3" suggesting that my override method did not get invoked till after the items were created! If there is a validation error, then the "is_valid was called" message appears after "Debug 1" as I would expect. So I am really surprised/confused what is going on here, and would like to know please if there is a special way that you need to go about overriding is_valid if the serializer involves … -
Lunching python script from Django View
I wrote an essential python script (data import) which executes a series of commands and, once it is executed, write in the console a message. I would like to implement this script in Django in order to run the script directly in a "frame console" without needing to prepare several JS/AJAX functions to write in the page the operation has been executed. Is this possible in a "simple" way without using sockets or any other tricky method? Thank you -
deployed my website on heroku successfully but when i tried to run it i am getting internal server error
procedure i followed while deploying my website on heroku are . created a Procfile Contents of Procfile are web: gunicorn website.wsgi:application --log-file - then I have done some changes to my settings.py file and here is the settings.Py file """ Django settings for website project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j3t578bbmo+!bmmp27k3+d*nowwo%8y5k7-545j48_$)z0i#67' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','getmachine.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django_countries', 'core', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries':{ 'cart_template_tags': 'core.templatestags.cart_template_tags', } }, }, ] WSGI_APPLICATION = 'website.wsgi.application' # Database … -
Django re_path picking up negative lookahead as capturing group and a argument for the view
I'm using a urlpattern like so urlpatterns += [ re_path(r'^(?!(?:api/|backend/))', include('an_app.urls')), ] It is so that it doesn't route paths starting with api/ or backend/. I have a specific requirement that needs this pattern, and I can't solely rely on ordering the paths to achieve this (this path captures URLs on / and sends them to a view that renders a SPA). Unfortunately, the Django URL resolver is picking up the negative lookahead (^(?!...) as a capturing group, and inserts a path variable into the view. If I run python manage.py show_urls (from django-extensions): /<var>app/ an_app.views.SomeView an_app:home The "group" behind the ^app/ in the regex is not a capturing group, and the paranthesis is there to denote a negative capturing group (i.e. the path doesn't start with backend/ or api/). But it seems like Django is picking it up as a capturing group and inserts a variable into the URL. Do you know how to configure this so it doesn't get picked up? -
How to save image in django without uning django forms
Model class Property(models.Model): property_id = models.BigAutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=30, default='Public') title = models.CharField(max_length=30, default='') image1 = models.ImageField(upload_to="properties/images", default='', null=True) image2 = models.ImageField(upload_to="properties/images", default='', null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image1: img1 = Image.open(self.image1.path) if img1.height > 1500 or img1.width > 1500: output_size = (1500, 1500) img1.thumbnail(output_size) img1.save(self.image1.path) if self.image2: img2 = Image.open(self.image2.path) if img2.height > 1500 or img2.width > 1500: output_size = (1500, 1500) img2.thumbnail(output_size) img2.save(self.image2.path) View def post(self, request): status = request.POST.get('status') title = request.POST.get('title') image1 = request.FILES.get('image-1') image2 = request.FILES.get('image-2') if Property.objects.all(): pid = Property.objects.all().last().property_id + 1 else: pid = 0 Property(property_id = pid, author = request.user, status = status, title = title).save() p = Property.objects.all().filter(property_id = pid)[0] if image1: p.image1 = image1 if image2: p.image2 = image2 p.save() return redirect('add_item') HTML <input name="image-1" type="file"> <input name="image-2" type="file"> With this is code i can add Product_id, author, status but image1 and image2 is not uploading to properties/images when i open to this model in django-admin then its look like a blank image field -
So I am getting an Attribute error in in Django when I try to link a form to a view function
The error is this: File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\xml\etree\ElementInclude.py", line 136, in _include if e.tag == XINCLUDE_INCLUDE: AttributeError: 'str' object has no attribute 'tag' This error occurred when I tried to link one urls.py file to another urls.py file. Here is the file: urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.homepage), path('about/', views.about), path('addinfo/', views.addinfo), path('register',include('register.urls')) ] Specifically, when I added the last line, I got the error. Any idea what might cause this error? -
What is the best approach to attain multi-tenancy in Django?
I'm using django as an API server(using DRF) and admin dashboard with Postgres DB. The problem is I'll have multiple tenants and I want to follow a total separation of concern flow. Data from one tenant should not in any way be accessible to the other. Example Scenario: Say I have multiple Institutes as my clients and every institute will have all of their students onboarded on my platform. No institute should be able to access other's data. I can think of 2 approaches: 1. Extending ModelAdmin for Admin pages and for the APIs I can get the tenant associated to a particular user from the request. In this approach, I'll have to check for the tenant of a user in every modelAdmin class and get a filtered queryset in the def get_queryset() method def get_queryset(self, request): tenant = request.user.tenant # using related_name of foreignkey queryset = Course.objects.filter(tenant_id=tenant) And have to do this similarly in the list, create, update and destroy methods of the ModelViewSet class while creating APIs class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer permission_classes = (DjangoModelPermissions,) def list(self, request, *args, **kwargs): tenant = request.user.tenant queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(tenant__id=tenant) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) … -
How do I ensure consistency with Django's password reset email function
I am trying to use Django's built in password reset email function. The emails get sent for some user accounts but not others. All other email sending functionality on my app works - so I guess my settings are correct. I read that the user account has to have a 'usable' password so I tried changing that and then testing the reset function and still the emails do not deliver. I tested the reset function in the django shell with: >>> send_mail('Test', 'Test','MY_FROM_EMAIL_ADDRESS',['MY_TO_EMAIL_ADDRESS'], fail_silently=False) 1 As you can see the output from the shell command suggests that the email was send, but it was not received. Any ideas what may be causing the inconsistencies? -
how can I get specific foreign key field related to other model in django?
models.py class Product(DateTimeModel): product_id = models.CharField(max_length=200) product_name = models.CharField(max_length=200) def __str__(self): return self.product_id class ProductVariantsManager(models.Manager): def colors(self): return super(ProductVariantsManager, self).filter(variant_type='Color', approval_status = "Approved") class ProductVariants(DateTimeModel): product_id = models.ForeignKey(Product, related_name="product_variants", null=True, on_delete=models.CASCADE) variant_type = models.ForeignKey(VariantsType, null=True, on_delete=models.CASCADE) variant_value = models.ForeignKey(VariantsValue, null=True, on_delete=models.CASCADE) approval_status = models.CharField(max_length=50,choices=PRODUCT_STATUS,default="Pending",null=True, blank=True) objects = ProductVariantsManager() def __str__(self): return str(self.item_num) HTML <select name="color" class="form-control col-7" required> {% for i in product_id.productvariants_set.colors %} <option selected value="{{ i.variant_value}}">{{ i.variant_value}}</option> {% endfor %} </select> The Product has saved multiple variants based on colors. Here I need to get the variants_value(black, brown, red..) for the specific product's have. I have gotten nothing with this query. is there Foreign key problem querying here? Need help to get this correctly. -
The columns of my table do not have the proper width when I use the scrollX in my datatable
I am loading my datatable with ajax but the data in the columns is not being arranged correctly. Attached my code and photos of the problem. datatable libraries <link rel="stylesheet" href="{% static 'lib/datatables-1.10.25/css/dataTables.bootstrap4.min.css' %}"/> <link rel="stylesheet" href="{% static 'lib/datatables-1.10.25/plugins/fixedcolumns-4.0.1/css/fixedColumns.bootstrap4.css' %}"/> <link rel="stylesheet" href="{% static 'lib/datatables-1.10.25/plugins/responsive-2.2.9/css/responsive.bootstrap4.min.css' %}"/> <script src="{% static 'lib/datatables-1.10.25/js/jquery.dataTables.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/js/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/plugins/responsive-2.2.9/js/dataTables.responsive.min.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/plugins/responsive-2.2.9/js/responsive.bootstrap4.min.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/plugins/fixedcolumns-4.0.1/js/fixedColumns.bootstrap4.js' %}"></script> my table in html <table style="width:100%" class="table table-bordered table-striped display nowrap" id="data"> <thead> <tr> <th>Número</th> <th>Fecha de registro</th> <th>Hora de registro</th> <th>Medio</th> <th>Referencia</th> <th>Proceso</th> <th>Parametros</th> <th>Respuesta</th> <th>Resuspensión</th> <th>Estado</th> </tr> </thead> <tbody> </tbody> </table> El code of my datatable tblSuspension = $('#data').DataTable({ destroy: true, deferRender: true, scrollX: true, fixedColumns: true, ajax: { url: pathname, type: 'POST', headers: { 'X-CSRFToken': csrftoken }, data: parameters, dataSrc: "", beforeSend: function () { loading_message('...'); }, complete: function () { $.LoadingOverlay("hide"); } }, columns: [ {data: "id"}, {data: "date_joined"}, {data: "time_joined"}, {data: "medium.name"}, {data: "reference"}, {data: "process.name"}, {data: "parameters"}, {data: "response"}, {data: "id"}, {data: "id"}, ], columnDefs: [ { targets: [-4], class: 'text-center', render: function (data, type, row) { return '<a class="btn btn-warning btn-xs btn-flat" rel="parameters"><i class="fas fa-align-justify"></i></a>'; } }, { targets: [-3], class: 'text-center', … -
Which timezone to use for all users aroung the world?
Right now I am using UTC as timezone. But I am staying in Bangladesh and It is ahead of 6 hours from server time. I am using a clock as UTC timezone it is also showing me time ahead of 6 hours. <Clock format={'HH:mm:ss'} ticking={true} timezone={'UTC'} /> Here, I want global timezone. I am in Bangladesh so I will see the bd time, if I am in Russia, then I will see time according to russia. so which timezone to use for that? -
Django Channels and Accessing Models
I am running Django 3.2.10 and I am using Django Channels with daphne and gunicorn. I can get my websocket code to run and function without issue but when I go to access any of my django models I hit a snag. I'm doing something like this: async def receive(self): modelselected = await database_sync_to_async(self.get_model)() def get_model(self): return MyModel.objects.all()[0] When I do this which is what the official docs suggest I do, I get the following error from daphne: daphne | ERROR Exception inside application: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? My Django application works perfectly fine and I connect to the database no problem. I am at a loss to what I'm doing wrong. And my Postgres is running on Port 5432. Any thoughts? -
Django: Computing new attribute before serving data as GeoJSON
I have a dataset of point locations (in this example, schools). Before serving this data as GeoJSON, I'd like to compute polygonal buffers around the points, and add those as an attribute. I know that I can use django.core.serializers.serialize to convert a QuerySet into the GeoJSON format that I need. I also know how to calculate the buffer (self.geometry.buffer), I just can't figure out how to string this all together. models.py from django.contrib.gis.db import models class School(models.Model): name = models.CharField(max_length=50) geometry = models.PointField() def compute_buffer(self, radius): self.buffer = self.geometry.buffer(radius) views.py from django.core.serializers import serialize def data(request): geom_as_geojson = serialize('geojson', School.objects.all()) return HttpResponse(geom_as_geojson, content_type='json') -
How to update django local cache every day using django background tasks?
I'm using django local cache in my application. There is a certain table in my database which is used in high frequency, e.g. fetch top 10 records from a specific table. So, every time this runs a query in my DB to get this data. Also, I'm using django background tasks which updates this table every day. So, this top 10 records of the table will remain the same for a day and I want to keep this in some local cache so that it can be fetched directly from the local cache instead of running another query. I want to implement something like below, the refreshCache function should update the cache. But how to trigger it at certain time with django background tasks so that the cache gets updated in django server too? [Background task runs in a separate thread and triggered manually using python manage.py process_tasks] from django.core.cache import cache def refreshCache(): cache.set("TOP_10_RECORDS", MY_TABLE.objects.all()[:10]) Any alternative of the above solution is welcome! -
How can I join two model in django
I want to join two model. I am using postgresql. But the problem is I am not using any foreign key or many to field. But I am using same unique field for both table. So I want depends on thats field I can query from both table. "invoice" is the field. My models are class Salesinvoice(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) customer = models.CharField(max_length=100) product_name = models.CharField(max_length=80) price = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) quantity = models.IntegerField(default=0) class Salespayment(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) payment = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) What should be my Views for join above both table depends on invoice field. -
What is the best way to add a field from a non-related model to a serializer in drf? I can't change the db. SerializerMethod field created n+1 queries
I have two models. Model A and Model B. Both are related to each other however there is no relation at the model level. I can't make the changes to the models either because of the nature of my project. I need to add the related fields of Model B in the serializer of Model A. What is the best way to achieve this? When I tried using serializer method field I ran into the n+1 query problem. -
How to use make delete request of generic viewset without sending the pk
I am using django in the backend and react native in the frontend, I have a generic viewset with destroy, create mixins. In my use case, I make a post request when the user is logged in and then delete the same instance when he logged out. The problem is I don't know the pk of the created instance to send it in the delete request. Is there a way to know the pk of the created model instance to use it then in the delete request? NB: the model pk is automatically generated in Django, not a created field. The view is class DeviceViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = DeviceSerializer queryset = Device.objects.all()