Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: models.Model.objects.filter(pk) return nothing [closed]
I started learn Django framework. Following the official tutorial I have model Question that is derived from django.db.models.Model After all migrations, In views.py I created function called detail that is supposed to show me question by quest_id here is the code def detail(request, quest_id): by_id = Question.objects.filter(id=quest_id).first() by_index = Question.objects.all()[quest_id] response = f"Via filter \"{by_id}\" Via index \"{by_index}\"" return HttpResponse(response) In urls.py I added corresponding path to urlpatterns Next I added two records of Question to my database, but when I tried to Question.objects.filter(quest_id).first(), I've always get None even if I have Question with id=quest_id Here Is result of detail for id quest_id -
Index file shown but not the live website
enter image description hereI have deployed my website in the cpanel of namecheap but it shows the following problem in the given image. How can i fix it? I tried to change the .htacces file but it still did not work, please help me because i cannot fix this porblem by myself. -
django modelForm : dynamically adjust field according to related field
I've been working on a hospital project exercice and am wondering how to render a given field (model "doctor") according to a speciality selection: user has to select first a medical speciality and according to that one, the doctor's list will be dynamically updated. How can I design my modelForm to achieve that goal? Do I need some javascript embedded in the template file? Here is the related code in my django project: # models.py class Speciality(models.Model): specialite_id = models.AutoField(primary_key=True) nom = models.CharField(max_length=50, unique=True, verbose_name="Spécialité") def __str__(self): return f"{self.nom}" class Doctor(CustomUser): medecin_id = models.AutoField(primary_key=True) matricule_medecin = models.CharField(max_length=50, unique=True) specialite = models.ForeignKey(Specialite, on_delete=models.CASCADE) admin = models.ForeignKey(Administrateur, on_delete=models.SET_NULL, null=Tru e, blank=True) def __str__(self): return f"Dr {self.nom} {self.prenom}, spécialité : {self.specialite}" # forms.py class CreateSejour(forms.ModelForm): class Meta: model = Sejour fields = '__all__' widgets = {'date_entree': forms.SelectDateWidget(years=range(2015, 2025)), 'date_sortie': forms.SelectDateWidget(years=range(2015, 2025)), 'motif': forms.Textarea()} I don't see how to tackle this situation : do I have to implement some logic inside the modelForm or in my view? Thanks for your help. De716 Actually i'm stuck to that stage, my django experience doesn't allow me to address this and I have no experience in javascript -
Why do I have a Flutter web CORS issue despite having set CORS in django backend
I'm developing a Flutter web application that needs to make requests to a Django backend. However, I'm encountering a CORS error when I try to make a request. The error message is: Access to XMLHttpRequest at '<API_URL>' from origin 'http://localhost:63730' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I've already set up CORS in my Django settings as follows: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True Despite this, I'm still getting the same CORS error. Interestingly, I have other applications built with React and Vue that are able to make requests to the same Django backend without encountering any CORS errors. I'm not sure why my Flutter web application is encountering CORS errors while my React and Vue applications are not. Any help would be greatly appreciated. -
my Django registration page redirect isn't working
i'm trying to make a registration page for my Django project. When i compile the registration form it gives me the error in the image because it tries to go to this path (he doubles users/register): localhost/users/register/users/register/. How can i fix it? this is my code: Error image: users/view.py: def register_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('homepage') else: form = UserCreationForm() return render(request, "users/register.html", {"form": form}) users/urls.py: urlpatterns = [ path('register/', views.register_view, name="register"), ] main/views.py: def homepage(request): return render(request, 'homepage.html') main/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name="homepage"), path('music/', include('music.urls')), path('users/', include('users.urls')), ] -
Kubernetes Persistent Volume not shared when uploading a file with Django and Nginx
I created 2 persistant volumes, one for static files and other for media files. The static files one works just fine, nginx serves the data. For media volume, nginx does not see the uploaded file and the volume content does not update. The nginx conf is fine. The location works but volume does not contain the uploaded file. This is my media pv and pvc: apiVersion: v1 kind: PersistentVolume metadata: name: mediafiles-pv spec: storageClassName: manual capacity: storage: 1Gi accessModes: - ReadWriteMany hostPath: path: "/usr/src/app/backend/media" apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mediafiles-pvc namespace: default spec: storageClassName: manual accessModes: - ReadWriteMany resources: requests: storage: 1Gi volumeName: mediafiles-pv This is my deployment for backend (django): apiVersion: apps/v1 kind: Deployment metadata: name: backend labels: app: backend spec: replicas: 1 selector: matchLabels: app: backend template: metadata: labels: app: backend spec: volumes: - name: staticfiles persistentVolumeClaim: claimName: staticfiles-pvc - name: mediafiles persistentVolumeClaim: claimName: mediafiles-pvc containers: - name: backend image: loopedupl/backend:latest imagePullPolicy: Always ports: - containerPort: 8000 volumeMounts: - name: staticfiles mountPath: "/usr/src/app/backend/static" - name: mediafiles mountPath: "/usr/src/app/backend/media" and for nginx: apiVersion: apps/v1 kind: Deployment metadata: name: nginx labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: volumes: - name: … -
Pass requests from host to container with domain socket
I have uwsgi running on a docker container. Nginx running on host. Current setup: ;uwsgi.ini http-socket=:8080 With docker, I've forwarded the host's 8080 port to containers 8080 port. Nginx is configured like server { listen 443 ssl http2; server_name domain.example.com; location / { proxy_pass http://127.0.0.1:8080; } } This works fine, only problem: my port 8080 is exposed and I can directly request the port on the public IP. I should be able to use domain sockets to mitigate this, but I don't know how the set up would look like. Here's my half attempt: ; uwsgi.ini in container socket=/path/uwsgi.sock # nginx on host upstream prod_server { server unix:///path/uwsgi.sock; } server { listen 443 ssl http2; server_name example.domain.com; location { uwsgi_pass pror_server; } } Since nginx is in host, it will look for the path on host server, is adding the socket as a volume the right way to go? Is there another best practice? How would you recommend the setup? Thank you. -
I can't upload a file
I am writing an application in django, drf, I use drf_spectacular for documentation, the problem is downloading the file through the documentation, I do not need to process the file or store it, I just want to upload it and send it to another service. class PFX_key(serializers.Serializer): file = serializers.FileField() pin = serializers.IntegerField(required=False) description = serializers.CharField(required=False) @extend_schema(request=serializers.PFX_key) @action(detail=False, methods=['post'], parser_classes=[MultiPartParser,], serializer_class=serializers.PFX_key) def load_pfx_key(self, request: Request) -> Response: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: datatools.send_pfx_key(serializer.validated_data, self.request.user.username) except Exception as ex: raise ex return Response() The logic is fully working, all I need is the ability to upload files via drf_spectacular so that the fronts can work with it. I've tried adding different parameters, one of them even seems to fit the needs: OpenApiTypes.BINARY, but I get an error Please correct the following validation errors and try again. For 'file': Value must be a string. -
Django & React native, I can't login back after I logged out
const handleLogin = () => { axios.post('https://8d16-103-62-155-152.ngrok-free.app/api/auth/mobile-login/', { username, password }) .then(response => { // Clear existing user data AsyncStorage.removeItem('username'); // Assuming you stored the username in AsyncStorage // Set new username and navigate to Main screen setUsername(username); navigation.navigate('Main'); }) .catch(error => { Alert.alert('Login Failed', 'Invalid username or password'); }); }; THIS IS MY ERROR : Forbidden: /api/auth/mobile-login/ [29/May/2024 13:38:49] "POST /api/auth/mobile-login/ HTTP/1.1" 403 58 I can log in once but after I click logout I can't login again I think something is preventing it to access on my django after logging out. I just used navagation for my logout function -
What are the most common mistakes devs make? what can i learn from them? [closed]
I have joined a company as an intern. Recently, the manager told me to use best practices for coding etc.I wanna know what are professional best practices. I searched the net but couldn't find a satisfactory answer. ..... C'mon stack-overflow genies. -
How Do I Fix the errors in Django Models?
I am trying to create models in Django, but when I go to the admin page and click into the models, it gives me an error. Please see my code in python below. I also had problems when I was trying to make migrations, but it worked in the end, and in my admin panel. I could see the two models I created, but when I click into any of them, I got an error page. models.py from django.db import models from datetime import datetime import uuid # Create your models here. class ProductType(models.Model): Type_Name = models.CharField(max_length=200) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.Type_Name class ProductItem(models.Model): product_title = models.CharField(max_length=500, default="Product Name") product_type = models.ForeignKey('ProductType', on_delete=models.CASCADE) product_size = models.CharField(max_length=500, default="Product Size") product_finish = models.CharField(max_length=500, default="Product Finish") date = models.DateField(default=datetime.now, blank=False) quantity = models.IntegerField(default=0) unit_cost = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) unit_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) reorder_quantity = models.IntegerField(default=0) reorder_date = models.DateField(default=datetime.now, blank=False) image = models.ImageField(null=True, blank=True, default='404-img.png') id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.product_title admin.py from django.contrib import admin from .models import ProductItem, ProductType # Register your models here. admin.site.register(ProductItem) admin.site.register(ProductType) models.py from django.db import models from datetime import datetime import uuid # Create your models here. … -
Extracting text from PDF after uploading (Django app on AWS)
@login_required(login_url="/login/") def upload_view(request): posts = Temp.objects.all() common_tags = Temp.tags.most_common() if request.method == "POST": form = TempForm(request.POST, request.FILES, initial={"user": request.user}) if form.is_valid(): newpost = form.save(commit=False) newpost.slug = slugify(newpost.title) unique_slug = newpost.slug num = 1 while Temp.objects.filter(slug=unique_slug).exists(): unique_slug = "{}-{}".format(newpost.slug, num) num += 1 newpost.slug = unique_slug newpost.user = request.user # Process the document before saving extracted_text = process_document( request.FILES["file_upload"], newpost.language ) # Save the post and the extracted text newpost.ocr_text = extracted_text newpost.save() # Save the file first form.save_m2m() notify_users_about_new_post(form) messages.success(request, "Your Post has been uploaded successfully.") else: messages.warning(request, "Upload unsuccessful. Please try again.") else: form = TempForm() context = { "posts": posts, "common_tags": common_tags, "form": form, } return render(request, "upload_file.html", context) Currently, users can upload files and it will be stored in S3. I want to extract the content from the file and store it in the mySQL database. I tried different ways and they all failed. I used the following code. It works when I am testing it locally, but fail to download in Production. urllib.request.urlretrieve( [link to S3 storage, where the document can be viewed publicly], "temp.pdf", ) I used boto3. It works when I am testing it locally, but fail to download in Production. import boto3 # … -
How to Write Tests for Password Recovery in Django?
Could you please recommend where to find tutorial examples on how to write tests for authentication in Django, especially for password recovery via email and ensuring that the password reset link is valid only once? I want to add testing to my project, but I lack experience with testing password resets. There are some bugs, and the status code in some places is not what is expected according to the unit tests. The link remains valid after setting a new password, although it stops being valid after setting a new password during manual testing. I would like to see examples of how password recovery is tested in a standard project. ChatGPT is not helping, absolutely useless idiot on this matter. -
Changing from abstractuser to abstractbaseuser mid project to remove username field
I created a project initially with abstractuser so I could add additional fields to users profiles as well as set session variables during user login. Ive realised that abstractuser still has a need for the username field even though I have set authentication field to be email. I have tried setting username = None in the model but it throws an error during makemigrations saying unknown field 'username' specified for CustomUser. If I change the base class from abstract user to abstractbaseuser I still get the error mentioned above when makemigrations. code below, help would be very appreciated. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') user = self.model(email=self.normalize_email(email), **extra_fields,) user.set_password(password) user.save(using=self._db) print("user save from UserManager.create_user method") return user def create_superuser(self, email, password=None, **extra_fields): user = self.create_user(email, password=password, **extra_fields,) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(unique=True, db_index=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone = models.IntegerField(null=False, blank=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] def __str__(self): return self.email … -
poorly executed ajax submission
I have a code in django and ajax which, although it works for me, it is supposed that if it creates a user it should give me the if response and it gives me the else response but with the message that "I created the user" however it should not be like that since it also takes the else if you see an error if the gmail already exists... how can I correct this?: var csrftoken = 'YOUR_CSRF_TOKEN_VALUE'; $(document).ready(function() { $('#registrar_usuario').submit(function(event) { event.preventDefault(); // Prevent default form submission var form = $(this); var csrftoken = form.find('input[name="csrfmiddlewaretoken"]').val(); // Validate passwords and required fields if (!validarCamposRequeridos()) { return; // Prevent AJAX request if validation fails } // Send AJAX request to validate email on server $.ajax({ url: '/login/', // URL of the 'validarCampos' view method: 'POST', data: { 'csrfmiddlewaretoken': csrftoken, 'email_usuario': $('#email_usuario').val(), 'nombre_usuario': $('#nombre_usuario').val(), 'fecha_nacimiento': $('#fecha_nacimiento').val(), 'password1': $('#password1').val(), 'password2': $('#password2').val(), }, dataType: 'json', success: function(response) { if (response.success && response.status === 200) { console.log("si ejecuta envio") // aqui se presenta el mensaje cuando deberia mostrar el que funciona xd $('#alertaError').css('color', '#29A52D'); $('#alertaError').text("Usuario creado correctamente!"); // Consider a slight delay if needed setTimeout(function() { $('#registrar_usuario').submit(); // Submit the form after a delay }, … -
django reverting change of user info
I want to change the user email (and other informations about the user) So I created a route for it: @login_required def change_email(request): email = request.POST['email'] if email != request.user.email: request.user.email = email request.user.save() return JsonResponse({ 'message': 'Email updated' }) On the frontend, I get the 'Email updated' message. When I render a template with request.user.email after the change, I can see the new email, but after I reload the page once more, the old value is back there. I tried to manually query the user with refresh_from_db and nothing. I also tried checking through the admin page, and when I check, the value IS updated and then the next requests STILL updated. So I believe that it's something to do with caching and when I manually lookup the cache updates correctly? -
pymysql.err.OperationalError: (1045, "Access denied for user 'Mikael'@'localhost' (using password: NO)")
I've seen many threads and solutions but none have worked for me. I'm trying to run migrations on my django project via Mac. After running python manage.py makemigrations, I get this return stack line 150, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1045, "Access denied for user 'Mikael'@'localhost' (using password: NO)") It made sense that I don't have permissions for my database, so I went ahead and granted privileges for the user stated above ('Mikael'@'localhost') via terminal. To do so, I logged into the root user to grant privileges to 'Mikael'. mysql -u root -p Then granted all privileges for the user grant all privileges on *.* to 'Mikael'@'localhost' WITH grant option; Yet I'm still getting access denied. If it weren't clear through the initial error (in title), I'm using pymysql. I've also granted privileges in user: 'Mikael' -
Creating an Ebola reporting System
[enterenter image description here image description here](https://i.sstatic.net/H3oS2DkO.png) I created the site for reporting and diagnosing ebola cases. it allows for registration of users as either provider or patient, but I get that error when someone tries to register or login. it was created using django and streamlit. -
Django Admin Interface: Understanding Form Saving Behavior with commit Parameter
I'm currently working with Django's admin interface and encountering some unexpected behavior related to form saving with the commit parameter. Here's what I'm trying to understand: Context: I'm using a custom form (DeckCreateForm) with a save method overridden to handle saving deck data. Within this method, I've set the commit parameter to False to prevent immediate database commits. Observation: Despite setting commit to False, when saving a form instance through the admin interface, it appears that the form data is being committed to the database. Understanding Needed: I'm seeking clarification on why the form data is being committed to the database even when commit is explicitly set to False. Additionally, I want to understand the factors that could influence the behavior of the commit parameter within the context of Django's admin interface. Efforts Made: I've reviewed the Django documentation regarding form saving and the admin interface but haven't found a clear explanation for this behavior. I've also examined my code and haven't identified any obvious bugs or misconfigurations. Request: I'm looking for insights or explanations from the Django community on how Django's admin interface handles form saving and the factors that might affect the behavior of the commit parameter. Additionally, … -
salut problement sur django
Hi please I can't share my project developing in django in network so that another machine can access it in the same network as me I don't know what to do I have already run on 0.0.0.0:8000 and in addition to this ALLOWED_HOSTS = ['*'] is configured comsa when I type the ip address of my pc on the other pc without the port I access apache2 but when I add the port it says that this site is inaccessible need to 'help Salut svp je n'arrive pas a partager mon projet developper en django en reseau pour que une autre machine y accede dans le meme reseau que moi je ne sais pas quoi faire j'ai deja run sur 0.0.0.0:8000 et en plus de cela ALLOWED_HOSTS = ['*'] est configurer comsa quand je tape l'adresse ip de mon pc sur l'autre pc sans le port j'accede a apache2 mais quand j'ajoute le port on dit que se site est inaccecible besoin d'aide -
How to Resolve HttpRequest AssertionError in Django Friend Request View?
I'm working on a Django project where users can send and accept friend requests. When a friend request is accepted, I want to add the sender and receiver to each other's friend list and send a notification. However, I'm encountering an error when trying to send the notification. Problem Description: When a user accepts a friend request, I want to add the sender to the receiver's friends list and vice versa. However, I get the following error: AssertionError: The requestargument must be an instance ofdjango.http.HttpRequest, not userauths.models.User. [28/May/2024 16:09:33] "GET /accept-friend-request/?id=8 HTTP/1.1" 500 121207 so let me provide the link api to the function path("accept-friend-request/", views.accept_friend_request, name="accept-friend-request"), let me provide the accept_friend_request function @api_view(['GET']) @login_required def accept_friend_request(request): if request.method == 'GET': sender_id = request.GET.get('id') receiver = request.user # Log the sender_id logger.debug(f"Sender ID: {sender_id}") try: # Retrieve the sender user from the database sender = User.objects.get(id=sender_id) # Retrieve the sender's profile sender_profile = sender.profile # Add sender's profile to receiver's friends and vice versa receiver.profile.friends.add(sender_profile) sender_profile.friends.add(receiver.profile) # Delete the friend request friend_request = FriendRequest.objects.filter(receiver=receiver, sender=sender).first() friend_request.delete() # Send notification send_notification(sender, receiver, None, None, noti_friend_request_accepted) data = { "message": "Accepted", "bool": True, } return JsonResponse({'data': data}) except User.DoesNotExist: logger.error(f"User with ID … -
Why isn't my nav updating after htmx trigger?
I have a django project with a left navbar list of projects. I am new to htmx and I'm using it to update the project list after a new project is created from a form. I can see the htmx trigger event and the payload looks correct and the target div element looks correct. However, the update doesn't occur. I've tried including from:body. I have a hx-target in the form and I generate the HX-Trigger in the view, but I'm not sure if that's correct. Here is my views.py: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from apps.projects.models import Project, ProjectUser from apps.projects.forms import ProjectForm from apps.teams.models import Team from apps.users.models import CustomUser from django.http import JsonResponse from django.db.models import Q from django.shortcuts import render, get_object_or_404, HttpResponse from .utils import is_htmx_request from django.template.loader import render_to_string import logging # Configure logging logger = logging.getLogger(__name__) @login_required def project_create(request, team_slug): print(f'made it in creaTE') team = Team.objects.get(slug=team_slug) form = ProjectForm(team=team) if request.method == "POST": form = ProjectForm(request.POST, team=team) if form.is_valid(): print(f'form: {form}') project = form.save(commit=False) project.team = team project.save() # Save the project to get a project_id members_ids = request.POST.getlist("members") add_from_projects_ids = request.POST.getlist("add_from_projects") # Add current user to the project if … -
In django path error when try to submit the normal user regitration from
typ<form action="register" method="post"> {% csrf_token %} <input type="text" name="first_name" placeholder="First name"><br> <input type="text" name="last_name" placeholder="Last name"><br> <input type="username" name="username" placeholder="Username"><br> <input type="email" name="email" placeholder="Email"><br> <input type="password" name="password" placeholder="password"><br> <input type="password" name="confirm_password" placeholder="confirm_password"><br> <input type="submit" name="submit" value="Register"> </form>e here def register(request): # print("in register") # if request.method=="GET": # return render (request,"register.html") if request.method=="POST": print("IN POST") first_name=request.POST.get('first_name') last_name=request.POST['last_name'] username=request.POST['username'] email=request.POST['email'] password=request.POST['password'] confirm_password=request.POST['confirm_password'] user=User.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name) user.save() print("User Created") return redirect(home) # if password==confirm_password: # if User.objects.filter(username=username).exists(): # print("Username Already Taken") # elif (User.objects.filter(email=email)): # print("Email Already Taken") # else: # user=User.objects.create_user(username=username,password=password,email=email,first_name=First_name,last_name=Lirst_name) # user.save() # print("User Created") # return redirect('/') # else: # print("Password and Confirm Password Does Not Match") else: return render (request,"register.html") Expecting redirect to home page but its showing error: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/register/register Using the URLconf defined in Finance_Tracker.urls, Django tried these URL patterns, in this order: [name='home'] register/ [name='register'] admin/ The current path, register/register, didn’t match any of these. -
How to use poetry in Supervisor
I am trying to run huey, precisely django_huey, but each time I try to connect to DB. in the background task, 'root' is used as the user for the DB. Other parts of the application work well with the database config in django settings, like migration, etc. [program:application] directory=/home/.../django_project command=/home/.../.cache/pypoetry/virtualenvs/..../bin/python /home/.../.../manage.py djangohuey --queue application user='...' autostart=true autorestart=true redirect_stderr = true stdout_logfile = /etc/supervisor/realtime.log environment=PATH="/home/.../.../lib/python3.12/site-packages" stopwaitsecs=30 # task @db_periodic_task(crontab(minute='*/1'), queue='application') def app_task(): # current date and time current_timestamp = timezone.localtime(timezone.now()) # get all event get_events = Mymodel.objects.order_by('-creation_time').filter( time_ends__lt=current_timestamp ) if get_events.exists(): ... Error: connection failed: connection to the server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "root" -
Django View Causing ConnectionError in Production When Fetching TMDB API Data
Problem I am encountering a ConnectionError when trying to fetch data from the TMDB API and add it to my database in a production environment. The error message indicates that the connection was reset by the peer: This issue does not occur in the local development environment. Below are the relevant parts of my views.py and nginx settings. Code Snippets views.py: def SeriesAddView(request): org = Org.objects.first() if request.method == 'POST': tmdb_id = request.POST.get('tmdb_id') reqUrl = f"https://api.themoviedb.org/3/tv/{tmdb_id}?language=en-US" headersList = { "accept": "application/json", "Authorization": f"Bearer {org.tmdb_token}" } payload = "" series_details = requests.request("GET", reqUrl, data=payload, headers=headersList) update_series = Series.objects.filter(tmdb_id=tmdb_id).first() if series_details.status_code == 200: data = series_details.json() genre_data = data["genres"] genre_list = [] for genre_data in genre_data: genre_id = genre_data.get("id") genre_name = genre_data.get("name") if genre_id and genre_name: genre = Genre.objects.filter(genre_id=genre_id).exists() try: genre = Genre.objects.get(genre_id=genre_id) except Genre.DoesNotExist: genre = Genre.objects.create(genre_id=genre_id, name=genre_name) genre_list.append(genre) # Check if the poster image already exists img_path = data["poster_path"] poster_path = f"media/posters/tv{img_path}" if not os.path.exists(poster_path): # Save the poster image locally poster_url = "https://image.tmdb.org/t/p/original" + img_path poster_response = requests.get(poster_url) if poster_response.status_code == 200: with open(f"media/posters/tv/series{img_path}", 'wb') as f: f.write(poster_response.content) if update_series: # Update the existing movie update_series.adult = data["adult"] update_series.title = data["name"] update_series.original_title = data["original_name"] update_series.overview = data["overview"] update_series.release_date = …