Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
xhtml2pdf Django how to make a grid
I am trying to make a pdf with a grid system of 4x5 on each page. The problem is the amount of text on each tile can vary, and what I've noticed when using a table is when there's little text the table's columns will shrink, and when there's too much text the table's columns will expand onto another page. I need the columns to be a fixed size and preferably for the text in columns to shrink to fit. Any ideas? Thanks. -
Django login messages not being delivered as expected
I'm building a Django project and I have a Django app for the login, which I called members. The project is behind the login, so all the URLs redirect to the login page if the user is not logged. If the user inputs an existing user and password, the user can access to the site. This workd OK. If the credentials are wrong, I want the app to send back a message to the user, something like "Your credentials are wrong, try again", but I'm not getting this to work, even if I copied and pasted from the official documentation. My view: def login_user(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) else: messages.error(request, 'Credenciales inválidas.') My base template, which other template extends: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Mapa Primera Infancia: Login</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="{% static 'login.css' %}" /> </head> <body> <div class="msg"> {% for message in messages %} <div class="alert alert-info">{{message}}</div> {% endfor %} </div> {% block content %} {% endblock %} </body> </html> URLs of the members app: urlpatterns = [ path('login_user/', views.login_user, name='login'), ] I don't know … -
How to run Django in a Docker container with a remote PostgreSQL database?
I'm trying to compose a Django container that connects a remote PostgreSQL database with sslmode=require on port 25060. Everything looks fine during the build and the container is running with its peers. However, when I try to migrate the Django models it throws an error : $ docker-compose exec django python manage.py migrate [...] psycopg2.OperationalError: could not connect to server: Connection timed out Is the server running on host "db-postgresql-fra1-controller-do-user-12355871-0.b.db.ondigitalocean.com" (164.92.230.148) and accepting TCP/IP connections on port 25060? I exposed port 25060 in the docker-compose.yml and opened the port in the Docker host with sudo ufw allow 25060 but it keeps saying the same message. In parallel, the container of the Celery worker output is: Waiting for PostgreSQL to become available... Finally, I deactivated the /start command that wait until the database is ready before launching the container, just to check, but it doesn't change. How can I do that ? settings.py DATABASES = { "default": { "ENGINE": 'django.db.backends.postgresql', "NAME": os.environ.get("PSQL_DATABASE"), "USER": os.environ.get("PSQL_USER"), "PASSWORD": os.environ.get("PSQL_PASSWORD"), "HOST": os.environ.get("PSQL_HOST"), "PORT": os.environ.get("PSQL_PORT"), "OPTIONS": {'sslmode': 'require'}, } } .env PSQL_DATABASE=defaultdb PSQL_USER=username PSQL_PASSWORD=password PSQL_HOST=db-postgresql-fra1-controller-do-user.db.ondigitalocean.com PSQL_PORT=25060 docker-compose.yml version: '3.8' services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: controller command: /start volumes: - .:/app ports: - 8011:8000 … -
How to execute code whenever a Stripe session has been paid
I am using Stripe to integrate payments in my e-commerce website and Django as a web framework and I would like to create a custom administration site to manage the store, therefore I want to create a Command model whenever a stripe session has been paid. from .models import Command # I have a Command model class CommandView(views.APIView): def post(self, request, format=None): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'some price id', 'quantity': 1, }, ], mode='payment', success_url='http://localhost:3000/success/{CHECKOUT_SESSION_ID}', cancel_url='http://localhost:3000/store', billing_address_collection='auto', ) if checkout_session['payment_status'] == 'paid': # this will never work because the status in this view is always unpaid return Response({'url': checkout_session['url']}) except Exception as e: return Response({'error': e}) The solution I found is to execute the code in the success_url view but I'm wondering if it's possible to pay and to avoid getting into this url like immediately closing the tab... And maybe my solution of creating a Command model to see details of a command in the administration like color of product... is wrong, can you give some advices. -
Best practice how to send Django app logs to phone
I would like to send my logs from my Django app to my phone. I thought of using slack mail integration to send mails to a dedicated channel but this is only available in the paid slack version. Do you have any ideas with what kind of setup I could achieve this? I don't want to use plain mail since this is too spammy... Discord is also not working well with the webhook since it only pushed all 30 mins. Thanks and all the best -
Django search in one to one field
Wanna do search field by multiple fields from different classes in models. So I have model 1 class Man(models.Model): name = models.CharField(max_length=80) date = models.DateField() And model 2 class Data(models.Model): man = models.OneToOneField( Man, on_delete=models.CASCADE, primary_key=True ) data = models.JSONField(null=False) And I'm trying to create search for field Man.name and then for some fields from JSON blob. My views.py class DataList(generics.ListAPIView): search_fields = ['man.name'] filter_backends = (filters.SearchFilter, ) queryset = Data.objects.all() serializer_class = DataSerializer But when I'm trying to run it I have an error cause it can't access field man.name. So how can I acces it for searching? -
Activate account HTML email in Django
I have a Django App that lets users to register to the system. After the user register via a form receive a email with an activation link. The app works very well, but I want to send the user an HTML mail, not only plain text. I use an template to provide fields to be filled. The problem I face is how to provide the uuid and token in an HTML template in an activate link. I've reading about the send_mail() function, but I don't understand how to use for my purpose. I'm using Django 3.2.8. Show my code: myApp/urls.py path('registro/<str:usuario>', views.registro, name='registro'), path('activate/<uidb64>/<token>/', views.activate, name='activate'), path('esperaconfirmacionregistro/', views.esperaConfirmacionRegistro, name='esperaconfirmacionregistro'), path('confirmacionregistro/<str:status>', views.confirmacionRegistro, name='confirmacionregistro'), acc_active_email.html {% autoescape off %} Saludos, {{user.first_name}} {{user.last_name}}. Por favor da click en el enlace para confirmar tu registro, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} views.py def registro(request,usuario): if request.method == 'POST': form = FormularioAutoRegistro(request.POST, initial={'usuario':usuario}) if form.is_valid(): user = form.save() current_site_info = get_current_site(request) mail_subject = 'Activar cuenta de usuario' message = render_to_string('myApp/acc_active_email.html', { 'user': user, 'domain': current_site_info.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() form = FormularioAutoRegistro(initial={'usuario':''}) return redirect('esperaconfirmacionregistro') else: form = FormularioAutoRegistro(initial={'usuario':usuario}) return render(request, … -
How to change default text in django form?
I would like you to help me change the default text in the forms created by django in the foreign key fields for a custom text. Description of part of the content of Models.py class Historial(models.Model): id_historial=models.AutoField(primary_key=True) id_equipo=models.ForeignKey("Equipo", on_delete=models.CASCADE, verbose_name="Numero Serial de la computadora") id_usuario=models.ForeignKey("Usuario", on_delete=models.CASCADE, verbose_name="Nombre del usuario") fecha_entrega = models.DateField ('Fecha de entrega', auto_now=True , auto_now_add=False) fecha_devolucion = models.DateField('Fecha de devolucion', auto_now=True , auto_now_add=False) qr_code = models.ImageField(upload_to="CodigosQR") recibido=models.BooleanField(default=False) class Meta: verbose_name="Historial" verbose_name_plural="Historial" def __str__(self): return f"{self.id_equipo}" Description of part of the content of Forms.py class HistorialForm(forms.ModelForm): id_equipo = forms.ModelChoiceField(queryset=Equipo.objects.filter(Prestado=False).filter(basura_electronica=False)) id_usuario = forms.ModelChoiceField(queryset=Usuario.objects.filter(allow=True).filter(activo=True)) def __init__(self, *args, **kwargs): super(HistorialForm, self).__init__(*args,**kwargs) self.fields['id_equipo'].widget.attrs['class'] = 'form-control' self.fields['id_equipo'].widget.attrs['placeholder'] = 'Numero serial de la computadora' self.fields['id_usuario'].widget.attrs['class'] = 'form-control' self.fields['id_usuario'].widget.attrs['placeholder'] = 'Nombre del usuario' class Meta: model = Historial fields = [ "id_equipo", "id_usuario", ] labels={ "id_equipo":"Numero serial de la computadora", "id_usuario": "Nombre del usuario", } Description of part of the content of Views.py class ListadoHistorial(ListView): model=Historial form_class=HistorialForm template_name="prestamos/listar_prestamos.html" context_object_name="prestamos" queryset=None def get_queryset(self): return self.model.objects.all() def get_context_data(self, **kwargs): contexto={} contexto["prestamos"]=self.get_queryset() contexto["form"]=self.form_class return contexto def get(self, request, *args,**kwargs): return render(request, self.template_name, self.get_context_data()) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect("equipo:listar_prestamos") Description of part of the content of prestamo.html {% extends "index.html" %} … -
Django - poll - listing choices based on login user detail
Hy, I created a poll and the page of the poll can be accesed only if the user have a magiclink(made with django-sesame). After open that page using that maginlink i know witch user is, because when link is generated it incorporate the user information and include in that link. The obtions/choices (participanti) of the poll contain name and departemnt (dep_participant)field/value. The users also has and departemnt value (departament). So, the issue/question : in that page o the poll i want to show the name and departemnt for all obtions/choices (participanti) exept the obtions/choices (participanti) with the same department as the login user. I don't know how to make the query in view or forloop in template with that rule. With another words: if the user logged in is from department "hr" i want to show in the template all the choices/options from that poll for all department except those from "hr". Please help me with a solution. Thank you Below find my settings users models.py class UserVot(AbstractUser): departament = models.CharField(max_length=100, null=True, blank=True) rol = models.CharField(max_length=100, null=True, blank=True) poll models.py class Campanie(models.Model): ..... class Participanti(models.Model): campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE) nume_participant = models.CharField(max_length=200, verbose_name='nume') dep_participant = models.CharField(max_length=200, verbose_name='departament') votes = models.IntegerField(default=0) … -
How to get a list of objects using several model relationships in Django?
I have the following models : class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=16, unique=True, db_index=True) # ... class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) # ... class UserFollow(models.Model): follower = models.ForeignKey(User, related_name="follow_follower", on_delete=models.CASCADE) following = models.ForeignKey(User, related_name="follow_following", on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, editable=False) # ... I want to get the list of UserProfile of a user's followers from a username How can I accomplish this while optimizing database queries ? I use rest framework. -
connection refused django gunicorn nginx
I am getting following error when running search feature on my site (search feature makes api request to my api server): 2022/08/31 21:01:56 [error] 726#726: *23 connect() failed (111: Connection refused) while connecting to upstream, client: 11.111.111.111, server: api.mydomain.com, request: "GET /dividends/IBM/3/5 HTTP/1.1", upstream: "http://127.0.0.1:8001/dividends/IBM/3/5", host: "api.example.com", referrer: "example.com/" The supervisord gunicorn is up, the mongodb is up, and nginx is up I have the following /etc/nginx/sites-available/stocks_backend: upstream stocks_backend { server 127.0.0.1:8001 fail_timeout=4s; } server { server_name api.example.com www.api.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/stocks_backend; } location / { include proxy_params; proxy_pass http://unix:/etc/systemd/system/gunicorn.socket; proxy_ssl_server_name on; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by C> ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name api.example.com www.api.example.com; return 404; # managed by Certbot access_log /root/stocks_backend/log/nginx-access.log; error_log /root/stocks_backend/log/nginx-error.log; } I have tried things from Django gunicorn nginx (111: Connection refused) while connecting to upstream but when I remove http:// from the proxy_pass to … -
Django raises "django.db.utils.IntegrityError: duplicate key value violates unique constraint " after adding new field
After adding another field with parameter unique to my UserProfile model I get the following error when submitting the signup form which requires that field: django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_userprofile_pseudonym_key" DETAIL: Key (pseudonym)=() already exists. I flushed the entire database, deleted all migrations files and migrated everything entirely new and clean from scratch which didn't help. Everything worked well before adding pseudonym as additional field to the model. # html <form hx-post="{% url 'signup' %}" hx-swap="outerHTML" class="form shadow-2xl min-w-[360px] max-w-[360px] p-4 bg-surface rounded-lg text-white" > {% csrf_token %} <!-- form headline --> <h1 class="form-headline text-2xl text-surface-dark text-center mb-2">Create a new account</h1> {% if form.errors %} <div class="error-wrapper mb-2 p-2 bg-error rounded text-white"> <div class="errors text-center">{{ form.errors.pseudonym }}</div> <div class="errors text-center">{{ form.errors.email }}</div> <div class="errors text-center">{{ form.errors.password2 }}</div> </div> {% endif %} <div class="username-wrapper field-wrapper mb-2"> <div class="tag name-tag p-1 text-sm">{{ form.pseudonym.label }}*</div> <div class="input text-woys-purple text-surface-dark">{{ form.pseudonym }}</div> </div> ... </form> # forms.py class SignUpForm(UserCreationForm): pseudonym = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': tailwind_class})) email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'class': tailwind_class})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) class Meta: model = get_user_model() fields = ('email', 'password1', 'password2') # models.py class UserProfile(AbstractBaseUser, PermissionsMixin): # Unique identifier id = models.UUIDField(primary_key=True, … -
No 'Access-Control-Allow-Origin' header is present on the requested resource CORS error only for certain endpoints - React/DRF
I'm getting the following CORS error: Access to fetch at 'https://___backend.herokuapp.com/api/tickets/21/' from origin 'http://___frontend.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I believe all my django-cors-header settings are correct: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["https://____frontend.herokuapp.com"] CSRF_TRUSTED_ORIGINS = ["https://____frontend.herokuapp.com"] CORS_ALLOW_HEADERS = DEFAULT_HEADERS #this list includes Access-Control-Allow-Origin CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] The cors headers middleware is on top of the list and it's in installed apps. The weird part is that I'm only getting this error for 2 endpoints even though I'm using the exact same request options on the frontend: const requestOptions = { method: 'GET', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Authorization': `Token ${localStorage.getItem('token')}` } } I'm really confused as to how API calls to other endpoints can work fine but not for these 2. -
Django IIS is giving me a bad gateway error http platform handler
hello i am trying to deploy my Django app on IIS. I am trying to use http platform handler after being told that wfastCGI is deprecated. after changing my config file i tried to run my website on localhost it loads for a long while and gives me a bad gateway error. I am following this tutorial: https://medium.com/@akshay.mewada7/host-flask-and-django-web-application-with-windows-iis-httpplatformhanlder-83e831ce91bc <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <httpPlatform startupTimeLimit="10" startupRetryCount="10" stdoutLogEnabled="true" processPath="C:\Python310\python.exe" arguments="manage.py runserver"> <environmentVariables> <environmentVariable name="foo" value="bar" /> </environmentVariables> </httpPlatform> </system.webServer> <location path="" overrideMode="Deny"> <system.webServer> </system.webServer> </location> <location path="" overrideMode="Allow"> <system.webServer> <handlers> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </location> </configuration> is there something i can do to fix this -
How should I store encrypted files in Django?
I have a program that encrypts user uploaded files and I want to know where is the most secure place to store the encrypted file. After the file has been uploaded I encrypt the bytes which means that I can't use the default File upload system Django uses. The options I have thought of are: As a .txt file in the server (connected to Django by using the default File upload system) Save as a text input in the database (this will be completely encrypted) Which one of these are more secure and best for use, I also would like to know if there are any more ways of storing this encrypted file. Thank you -
Django dynamic template
is it possible to make a dynamic tag inside a if tag my view is this {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Leitung_der_Klasse}}</td> <td>{{Ansicht.Funktion}}</td> <td>{{Ansicht.Nname}}</td> <td>{{Ansicht.Vname}}</td> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK.{{DYNAMIC}} %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} I want filter this by date. Like an input for date and it would show my <td> like I have it in my template possible? -
Problems with edit button in Django
i'm novice and just trying Django functionality. I create button to edit value in db in Django, but it doesn't work write. Problem in that: when i press the button (from notes.html), it's redirect to page edit_note.html, but values in fields is empty. When i manually press adress in browser, it work's normally. I don't understand where i maked mistake. in views.py: class EditNoteView(UpdateView): model = Notes form_class = NotesForm template_name = 'notes/edit_notes.html' context_object_name = 'note' def get_success_url(self): return reverse_lazy('edit_note', kwargs={'pk': self.object.pk}) in urls.py: urlpatterns = [ path('', home, name='home'), path('notes/', NoteView.as_view(), name='notes'), path('<int:pk>/edit', EditNoteView.as_view(), name='edit_note'), in notes.html: {% for i in all_notes %} <tr> <td>{{ i.notes_category }}</td> <td>{{ i.title }}</td> <td>{{ i.text }}</td> <td>{{ i.reminder_data_time }}</td> <td> <form action="{% url 'edit_note' i.id %}" method="post"> {% csrf_token %} <div class="btn-small-group"> <button type="submit">Edit</button> </div> </form> </td> <td> <div class="btn-small-group"> <button type="submit">Delete</button> </div> </td> {% endfor %} in edit_notes.html: <form action="{% url 'edit_note' note.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <div class="btn-small-group"> <button type="submit">Edit</button> </div> </form> enter image description here enter image description here -
How can I place something at the top of a queryset in Django Rest Framework?
I have a model Post with field pinned_until = models.DateTimeField(blank=True, null=True). Let's say pinned_until has any value that is before the current time (timezone.now()), I want it to go at the top of the queryset, so it is first in the list of serialized response data. How can I accomplish that? I know it has something to do with annotate, but I haven't been able to figure it out so far. -
From API to Django template to show different data while iterating
***This is view function*** def home_view(request): url = "https://random-recipes.p.rapidapi.com/ai-quotes/50" headers = { "X-RapidAPI-Key": "`enter code here`", "X-RapidAPI-Host": "random-recipes.p.rapidapi.com" } response = requests.request("GET", url, headers=headers).json() res = response context = {'res' : change_recipe(), 'iterator':range(0,11)} return render(request,'home.html', context=context) This is django template <div class="container" id="card" > {% for i in iterator %} <div class="card1"> <div class="card-header1"> <img src="{{res.image}}" alt="rover" /> </div> <div class="card-body1"> <h4> <a href="/article/" style="text-decoration: none; color: inherit; " >{{res.title}}</a> </h4> <p> An exploration into the truck's polarising design </p> <div class="user1"> <div class="user-info1"> <strong>By</strong> <a href="">Rachel Lucas</a> </div> </div> </div> </div> {% endfor %} </div> I want to show different data when iterating for loop in django template using api when I replace res with res[0] it show only one data in all card1/div after iterating for loop in django template, i want to show different data in different cards. -
JavaScript setting multiple choice input field on Leaflet marker click
I have an embedded Leaflet map in a Django app with markers that are identifying different sampling locations for a study. These locations each have a unique location ID. When any of these markers are clicked, a popup appears with a form. The form has a few fields, one of them being that unique location ID for the user to select (in a multiple choice, drop-down style field). What I want to happen is when a user clicks on a marker, the location ID field in that multiple choice field in the popup is set to the unique ID of that marker. I have tried setting the field like this in a marker.on('click') function document.getElementById('location').value = marker.feature.properties.Location_Identifier ,but when you view the value after this it is still blank. I think part of the problem may be the feature.properties.Location_Identifier is the actual location ID whereas in the form Django makes the multiple choice fields be enumerated so the value there may just be an integer so there is a mismatch happening for setting the value. If anyone has any insight I would be grateful. -
Serializing two CharFields into one object
I have serializer like this below. Now I have separated fields for store_photo and store_name. class ProductSerializer(serializers.ModelSerializer): store_photo = serializers.CharField(source='store.photo', read_only=True) store_name = serializers.CharField(source='store.name', read_only=True) class Meta: model = Product fields = ['store_photo', 'store_name', ...] Can I somehow serialize it together in one object? I mean something like this: store = {store_photo, store_name} class Meta: model = Product fields = ['store', ...] -
Where do I store the encryption key when encrypting in Django?
I am creating a website using Django, my website will encrypt uploaded files and another user can then download the files unencrypted. It's pretty straightforward encrypting in python, but where do I store the encryption key? I encrypt the files in case the database or source code has been compromised. Then I can't store the encryption key as a file or in the database. Where can I store the encryption key? Thank you -
Django Framework or Not
Hello guys I'm working on a survey form website with DJango And I want user to generate a code to embed on their website Examples <!-- Start of HubSpot Embed Code --> <script type="text/javascript" id="hs-script-loader" async defer src="//js-na1.hs-scripts.com/22614219.js"></script> <!-- End of HubSpot Embed Co <script src="//code.tidio.co/uqkwgjeoo7leire6zsukpluyum8zqmme.js" async></script> And I don't know how to do it Will I use The Django Framework If yes drop resources to help me work it out (Without Framework) And still if no I don't still know how to do it DJango Drop resources to help me do it normal way in Django with framework -
Access static method variable in Generic APIView Post method
I have a custom static method in my GenericAPIView previously the calls create and complete() were in try and except for each task it tries and except logger.error(called) in post method instead i removed try and except from each task and created new method and catching the exception while calling the method but its not working how can i access task used in my_static_method in my post method in exception class MyAPIView(GenericAPIView): @staticmethod def my_static_method(arg1, arg2, arg3): if arg3 and not arg2.value: task = task1(arg1) task.create() task = task2(arg1) task.complete_task() if arg1.somevalue() or arg1.someotherValue(): task = task3(arg1=arg1) task.complete_task() def post(self, request, *args, **kwargs): try: self.my_static_method(self.arg1, arg2, self.arg3) except Exception: logger.error(f"Error executing the {task.__class__.__name__}", exc_info=True) -
How to get last created item's id by django restframwork in react
def create(self, request): serializer = TodoItemSerializer(data=request.data) if serializer.is_valid(): device = serializer.save() device = device.id return Response(device, status=status.HTTP_201_CREATED) it is working. How can i get this device item in react i have a api call like this, i tried console.log(response.device) but returned "undefined". How can i access the device item ? const response = await fetch("http://localhost:8000/api/todoitems/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: this.state.title, description: this.state.description, due_date: this.state.date, creator: this.state.userId }) }); if (response.status === 201) { console.log(response) toast.success('Success', { toastId: 'success1', position: toast.POSITION.TOP_CENTER }) } else { alert("Something went wrong!"); }