Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where to put crucial credentials?
Should I put all API keys etc. inside .env and git ignore it or use the environment variables? As far as I understand .env is just the equivalent of putting passkeys into the environment, but it is easier accessible from the root directory. -
signals not working in my vendor management app django app and i tried to import vendor_app.signals in app.py but error is showing
I have create three models vendor, purchase order and historical performance where historical performance model update from changes and values of purchase order for which i created signal file seprately and added the logic to update fields.I tried to configure signals in my apps.py file in vendor_app directory for which i am getting error"no module fine vendor_app" . I added vendor_app in my vendor_management/settings.installed app. I can't figure out where is problem. models.py code from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from django.dispatch import receiver import datetime from django.db.models.signals import post_save # Creating Model for storing user token @receiver(post_save, sender=User) def create_auth_token(sender, instance, created=False, **kwargs): if created: Token.objects.create(user=instance) # Creating model for vendor class Vendor(models.Model): name = models.CharField(max_length=255) contact_details = models.TextField() address = models.TextField() vendor_code = models.CharField(max_length=50, unique=True) on_time_delivery = models.FloatField(default=0) quality_rating_avg = models.FloatField(default=0) average_response_time = models.FloatField(default=0) fulfillment_rate = models.FloatField(default=0) # Creating model for Purchase Order class PurchaseOrder(models.Model): STATUS_CHOICES = [ ('pending', 'Pending'), ('completed', 'Completed'), ('canceled', 'Canceled'), ] po_number = models.CharField(max_length=50, unique=True) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) order_date = models.DateTimeField(default=datetime) delivery_date = models.DateTimeField(null=True) items = models.JSONField() quantity = models.IntegerField() status = models.CharField(max_length=50, choices=STATUS_CHOICES) quality_rating = models.FloatField(null=True, blank=True) issue_date = models.DateTimeField() acknowledgment_date = models.DateTimeField(null=True, blank=True) class HistoricalPerformance(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) … -
How to create distinct items using FactoryBoy in Django Rest Framework
I have the following code. #factories.py fake: Faker = Faker() class CollectionFactory(factory.django.DjangoModelFactory): class Meta: model = Collection django_get_or_create = ('title', ) title = fake.word(part_of_speech='noun') class ProductFactory(factory.django.DjangoModelFactory): class Meta: model = Product # django_get_or_create = ('title',) title = fake.word(part_of_speech='noun') slug = fake.slug() description = fake.text() unit_price = fake.pydecimal(max_value=1000, min_value=1, right_digits=2) inventory = fake.random_number(digits=4) last_update = fake.date_time_ad(start_datetime=datetime(1998, 1, 1, 1, 1, 1), end_datetime=datetime.now()) # collection = CollectionFactory() collection = factory.SubFactory(CollectionFactory) #test_product.py @pytest.mark.django_db class TestListProduct: def test_product1(self, api_client, product_factory): product_factory: ProductFactory = product_factory product_factory.create_batch(10) prods = Product.objects.all() # Problem: all of these products have the same title cols = Collection.objects.all() assert Product.objects.count() == 1 But the problem is that when I am doing the test all of the products are identical, I need them to at least have different titles. How do I achieve this? -
Problem with Django class-based LogoutView in Django 5.0
I used Django class-based login and logout views by "django.contrib.auth.urls", login feature works correctly, but when logging out via the link "http://127.0.0.1:8000/accounts/logout" it returns an http 405 error page, saying "method not allowed (GET)". I found out this logout feature was available in django 4.0 but in django 5.0 it's removed. Support for logging out via GET requests in the django.contrib.auth.views.LogoutView and django.contrib.auth.views.logout_then_login() is removed. -djangoproject.com How can I fix it? I think I should somehow make it use POST request instead GET request when loging out but don't know how. -
Why wagtail rich text content not being displayed in the front-end in the way expected?
I am using wagtail Rich Text Field to create content for my website paragraph = RichTextField() However, I am getting an issue where lists are not being displayed in the front-end and the font color of the content written as rich text is different from the rest of the content. Is there something that I am doing wrong or may there be something I must do such that the The rich text content is displayed the way I write it in the admin panel and such that the rich text content is displayed with the same font color and size as the rest of the content? I have used the richtext filter in my template: {{ block.value|richtext }} How I entered the content: admin panel where i entered content How content was displayed: how content is being displayed -
Django : Serializer validation prevents my code from updating an existing object
I have a Django project that get some user data and store them in a database. I want my function to handle both Create and Update with the same method, so I created a view that inherit from UpdateAPIView class UserList(generics.UpdateAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer def put(self, request, *args, **kwargs): raw_user_serializer: RawUserSerializer = self.get_serializer(data=request.data) raw_user_serializer.is_valid(raise_exception=True) # Fail when user already exists raw_user: RawUser = RawUser(**raw_user_serializer.validated_data) // Some custom computing # Create or update raw_user self.perform_update(raw_user_serializer) return JsonResponse({'user_id':raw_user.id}, status = 201) class UserDetail(generics.RetrieveAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer I think that the use of a UpdateAPIView and the function perform_update() is good. It works well when the user doesn't exist already, but when I try to create a new user with the same primary key, I get : Bad Request: /api/profiling/users/, with the following response : { "id": [ "raw user with this id already exists." ] } It look like it fails on raw_user_serializer.is_valid(raise_exception=True) instruction. How can I solve my issue ? (while keeping the validation of my object) -
my customuser (AbstractBaseUser) is not creating table in postgres and django rest framework
my CustomUser table is not being created in dbms when doing migrations it tell all ok but when running the project and going to api it fails to fetch dbms table from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField Create your models here. class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) # Add more fields as needed class CustomUser(AbstractBaseUser): UserName = models.CharField(null=True, blank=True, max_length=100, unique=True) FirstName = models.CharField(max_length=100,blank=True) LastName = models.CharField(max_length=100,blank=True) ContactNumber = PhoneNumberField(unique=True) Email = models.EmailField(unique=True) CompanyRole = models.CharField(max_length=100,blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'Email' and when running this it show "ProgrammingError at /hrms/api/users/ relation "hrms_customuser" does not exist LINE 1: ..."is_staff", "hrms_customuser"."is_superuser" FROM "hrms_cust..." -
HTMX get the text from inputfield for using in hx-get
<input type="number" x-model="inputValue" min="1" max="{{ page.paginator.num_pages }}" placeholder="Enter a number"> <button type="button" hx-get="?page={{ ????? }}">Go</button> here is the code extending it from the htmx example to create a go to page for partial load pagination https://github.com/adamchainz/django-htmx/tree/main/example The problem is that I am not able to configure hx-get to take the value of inputValue field. -
structlog bind method remembers previous user and logs with user_id, but after request finished it's not being cleared
I have bind user_id with structlog to log user_id like following in a middleware class StructlogMiddleware(MiddlewareMixin): def process_request(self, request): req = set_request_user(request) user_id = getattr(request.user, 'id', None) structlog.get_logger('django_structlog.middlewares.RequestMiddleware').bind(user_id=user_id) bind_threadlocal(user_id=user_id) MIDDLEWARE = [ ... "user_mngmt_app.custom_middleware.StructlogMiddleware", "django_structlog.middlewares.RequestMiddleware", .... ] for the first request made after app started, it logs prefectly it logs user_id=None before request is started, and prints actual id after request is started. Problem is for further requests, it logs previous user_id before request started, while it should be None. Id after request started is always ok. I want to reset/remove/clear user cached data after request is done. -
Refactring multiplies ifs
My current code is this class CounterFilters(TextChoices): publications_total = "publications-total" publications_free = "publications-free" publications_paid = "publications-paid" comments_total = "comments-total" votes_total = "voted-total" class SomeView: def get(self, request, format=None): user = request.user response_data = [] if "fields" in request.query_params: fields = request.GET.getlist("fields") for field in fields: if field == CounterFilters.publications_total: response_data.append({"type": CounterFilters.publications_total, "count": some_calculations1}) if field == CounterFilters.publications_free: response_data.append({"type": CounterFilters.publications_free, "count": some_calculations2}) if field == CounterFilters.publications_paid: response_data.append({"type": CounterFilters.publications_paid, "count": some_calculations3}) if field == CounterFilters.comments_total: response_data.append({"type": CounterFilters.comments_total, "count": some_calculations4}) if field == CounterFilters.votes_total: response_data.append({"type": CounterFilters.votes_total, "count": some_calculations5}) return Response(response_data) Based on get-param fields (which is list) I fill response_data data with some calculations, different for each CounterFilters.value . I'm wondering, if there is a way to avoid this big amounts of ifs ? -
How to add multiple parameters to a GET request in a django template?
I have a page with a table of objects. Users can choose a filter from a dropdown menu: <a href='?filter1=black'>Black</a> <a href='?filter1=white'>White</a> Which adds the filter into the GET request, like so: website.com/products?filter1=black Now I want users to be able to combine that with another filter: <a href='?filter2=black'>Small</a> <a href='?filter2=white'>Big</a> So that the GET request will look like this: website.com/products?filter1=black&filter2=small How does one usually go about this (preferably in django template language)? -
ERROR Exception in worker process from Digital Oceanś App Platform for Django web application
As per DO´s app platform documentation I am NOT creating repository because I have repository already in my Github account. When I deployed the app as per rest of the steps mentioned in the document, deployment was successful, but runtime log returned the following errors regarding gunicorn: [vksite] [2023-12-19 05:44:29] [2023-12-19 05:44:29 0000] 1 [INFO] Starting gunicorn 21.2.0 [vksite] [2023-12-19 05:44:29] [2023-12-19 05:44:29 0000] 1 [INFO] Listening at: http://0.0.0.0:8080 (1) [vksite] [2023-12-19 05:44:29] [2023-12-19 05:44:29 0000] 1 [INFO] Using worker: sync [vksite] [2023-12-19 05:44:29] [2023-12-19 05:44:29 0000] [14] [INFO] Booting worker with pid: 14 [vksite] [2023-12-19 05:44:31] [2023-12-19 05:44:31 0000] [14] [ERROR] Exception in worker process ........ [vksite] [2023-12-19 05:44:31] SystemError: initialization of _psycopg raised unreported exception [vksite] [2023-12-19 05:44:31] [2023-12-19 05:44:31 0000] [14] [INFO] Worker exiting (pid: 14) [vksite] [2023-12-19 05:44:31] [2023-12-19 05:44:31 0000] 1 [ERROR] Worker (pid:14) exited with code 3 [vksite] [2023-12-19 05:44:31] [2023-12-19 05:44:31 0000] 1 [ERROR] Shutting down: Master [vksite] [2023-12-19 05:44:31] [2023-12-19 05:44:31 0000] 1 [ERROR] Reason: Worker failed to boot. I´m wondering whether anyone has come across this issue? If you are, could you let me know if there is a remedy for the above error? -
Django count satisfied filters in queryset
Good day everyone. I am trying to learn python and django for a few days now and have come across a challenge. I would like to search a model, count the filters that was satisfied (like a score), then order them by that score in descending order. I tried the following: filter_count = 3 q1 = Q(fieldA__iexact='AAA') q2 = Q(fieldB__iexact='BBB') q3 = Q(fieldC__contains='CCC') qAll = q1 | q2 | q3 results = myModel.objects.filter(qAll).annotate( match_count=Count('id') ).order_by('-match_count') for result in results : print(result.name + " : " + str(result.match_count)) percentage_score = result.match_count/filter_count * 100 I would like something like: Item1 - 3/3 match, 100% match Item2 - 0/3 match, 0% match Item3 - 1/3 match, 33% match It "partially" works, but I am definitely missing something. Since Count is not working as I expected. I would greatly appreciate some advice/pointers. -
Deploying Django on A2 hosting
I was wondering if anyone has deployed a django web-site with A2 Hosting. I will use linux, and the Debian operating system. They do not allow a free trial to test, and I am a little cautious before I commit financially. The selection I would be choosing, would be one of the unmanaged VPS options. Appreciate any help, and interested in knowing if the customer service were informative. Cheers -
Django Elastic Beanstalk Static Configuration not working
I'm trying to deploy a Django application on Elastic Beanstalk, and had problems with my css files in the static folder generated by python3 manage.py collectstatic being read by my html templates. I digged deeper, and turns out when I SSH into the EC2 instance that is hosting my application, the file /etc/nginx/conf.d/elasticbeanstalk/01_static.conf contains location /static/ { alias /var/app/current/static; access_log off; } My application only works when I manually change this file to contain location /static/ { alias /var/app/current/static/; access_log off; } The only change here is that I added a trailing slash at the end of the alias. I looked this up more, and was recommended that I create a 01_static.config file in the .ebextensions directory within the root directory, which I did and populated with the following: files: "/etc/nginx/conf.d/elasticbeanstalk/01_static.conf": mode: "000755" owner: root group: root content: | alias /var/app/current/static/; However, this doesn't seem to do anything. Does anyone have solutions as to how I can add the trailing slash without manually SSHing into an EC2 instance on every deployment? Thanks in advance. -
CKEditor5: Image Upload Issue in Django (django-ckeditor-5)
I'm encountering an issue while integrating CKEditor5 into my Django project. Specifically, the image upload feature is not working properly. When I attempt to upload an image, I receive an alert message stating 'Couldn't upload file.' Additionally, my terminal displays the error 'Not Found: /ckeditor5/image_upload/ [18/Dec/2023 15:00:22] "POST /ckeditor5/image_upload/ HTTP/1.1" 404 4276.' It's strange because the image upload functionality only fails outside the Django admin page, where it works correctly. Could you advise on how to resolve this issue? class Meeting(models.Model): enter code here -
Django app not connecting to PostgreSQL in setup created via docker-compose
I am trying to run a Django app with a PostgreSQL database via docker compose. Here is my docker-compose.yml: version: '3.7' services: web: build: . volumes: - .:/immoscreen env_file: - .env # name of the env file environment: - APP_DB_ENGINE=${APP_DB_ENGINE} - APP_DB_HOST=${APP_DB_HOST} - APP_DB_PORT=${APP_DB_PORT} - APP_DB_NAME=${APP_DB_NAME} - APP_DB_USER=${APP_DB_USER} - APP_DB_PASSWORD=${APP_DB_PASSWORD} image: immoscreen_app ports: - ${DJANGO_APP_PORT}:${DJANGO_APP_PORT} expose: - ${DJANGO_APP_PORT} restart: "on-failure" depends_on: - db db: image: postgres volumes: - ./db/data/:/var/lib/postgresql/data/ - ./db/init.sql/:/docker-entrypoint-initdb.d/ env_file: - .env environment: - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - APP_DB_NAME=${APP_DB_NAME} - APP_DB_USER=${APP_DB_USER} - APP_DB_PASSWORD=${APP_DB_PASSWORD} ports: - 5432:5432 Here are the relevant parts of the .env file referenced in docker-compose.yml: # PORT to run Django app on DJANGO_APP_PORT=8000 # POSTGRES DB configuration APP_DB_ENGINE=django.db.backends.postgresql APP_DB_HOST=db APP_DB_PORT=5432 APP_DB_NAME=immohub APP_DB_USER=immohub APP_DB_PASSWORD=thepassword # POSTGRES DB configuration POSTGRES_PASSWORD=postgres The database is being initialized as expected with the initialization script stored in ./db/init.sql/. I can connect to the database with pgAdmin on the machine I am running this on with the following settings: Host: db Port: 5432 DB: postgres User: postgres Password: postgres However, the Django app in the web container fails to connect to the database. Instead, it returns the following stack trace: immohub-web-1 | Watching for file changes with StatReloader immohub-web-1 | Performing system checks... immohub-web-1 … -
How do I edit model field?
ocena field doesnt change models.py class Produkt(models.Model): id = models.AutoField(primary_key=True) nazwa = models.CharField(max_length=128) opis = models.CharField(max_length=128) cena = models.FloatField() class Ocena(models.Model): id = models.OneToOneField(Produkt, primary_key = True, on_delete=models.CASCADE) ocena = models.IntegerField(default = 0) def aktualizujOcene(self,rating): self.ocena += rating self.save() forms.py class OcenaForm(Form,): ocena = forms.IntegerField(max_value=5, min_value=1) views.py `method that show Produkt by ID` def pokazProdukt(request, produkt_id): try: produkt = Produkt.objects.get(id=produkt_id) komentarzForm = KomentarzForm() komentarze = Komentarz.objects.filter(produkt_id=produkt) try: oc = Ocena.objects.get(id = produkt) except Ocena.DoesNotExist: oc = Ocena() oc.save() oceny = [] for i in range(1, 6): oceny.append(OcenaForm(initial={'oceny': i})) return render(request, 'pokazProdukt.html', {'produkt': produkt, 'form': komentarzForm, 'komentarze': komentarze, 'oceny': oceny, 'oc': oc}) except Produkt.DoesNotExist: return render(request, 'listaProduktow.html') `method that edit field ocena in model Ocena` def dodajOcene(request, produkt_id): if request.method == 'POST': form = OcenaForm(request.POST) produkt = Produkt.objects.get(id=produkt_id) o = request.session.get(f'oceniono-{produkt_id}') if form.is_valid() and (o == None or o == False): oc = Ocena.objects.get(id = produkt) oc.aktualizujOcene(form.cleaned_data['ocena']) print("TESTSTSTS") messages.add_message(request, messages.SUCCESS, "Oceniono artykuł") request.session[f'oceniono-{produkt_id}'] = True return redirect(pokazProdukt, produkt_id=produkt_id) html code <div class="oceny"> <div class="oc"> <p>Ocena: {{ oc.ocena }} / 5</p> </div> <div class="ocena"> {% for o in oceny %} <form method="POST" action="{% url 'dodajOcene' produkt.id %}"> {% csrf_token %} {{ o.oceny.as_hidden }} <input type="submit" value="{% cycle '1' '2' '3' '4' '5' … -
How to Django Pagination
Am trying to make a website for branding products, so want the container to hold 8 items and clicks the pagination to see the other products Here is the view code `def index(request): # Retrieve all products from the database new_products = Product.objects.all() # Create a Paginator object with the products queryset and define the number of items per page page_items = Paginator(new_products, 8) # Display 8 products per page # Get the current page number from the request's GET parameters page_number = request.GET.get('page') try: # Get the Page object for the desired page number page_obj = page_items.get_page(page_number) except PageNotAnInteger: # if page_number is not an integer then assingn the first page page_obj = page_items.page(1) except EmptyPage: #if page is empty then return last page page_obj = page_items.page(page_items.num_pages) context ={'page_obj':page_obj} return render(request, 'Genesis/home.html',context)` here is the page code ` {% if new_products %} <div class="row" id="product-container"> {% for product in page_obj.object_list %} <div class="col-lg-3 col-md-6 mb-4"> <!-- Adjust the column classes as needed --> <div class="card"> <!-- Product image --> <div class="bg-image hover-zoom ripple ripple-surface ripple-surface-light" data-mdb-ripple-color="light"> <img src="{{ product.first_image.Product_Image.url }}" alt="Product Image" class="w-100" /> <a href="#!"> <div class="mask"> <div class="d-flex justify-content-start align-items-end h-100"> <h5><span class="badge bg-primary ms-2">New</span></h5> </div> </div> … -
Django: Get serialized object in save hook
Use case: On save for some of my models, I need to serialize them and send the serialized object somewhere (logging, emails etc). There's some additional things that need to happen with the serialized object. The important thing is that I need this serialized object on a save hook as there are multiple ways my model can be saved (via Rest, Django Admin, etc). However, since Django serializers import the model its serializing, this creates a circular reference. Before jumping to Signals, it should be noted that Signals have some limitations and are considered an anti-pattern. Ideally, I would like to use Django Lifecycle hooks, which are considered a more suitable and reliable hook at the model level. But this still doesn't solve the issue of calling a serializer on a save hook in a Django model. So besides explicitly calling the serializer and save methods at the View level, is there a way to serialize the object at the model's save operation? -
Make a Django application pip-installable with pyproject.toml?
I've got a couple Django projects that use the same 'shared application', which we will call shared-django-app. The shared application has it's own git repository. Recently, instead of having to run git clone after setting up the project to bring in the shared-django-app we have been considering adding it to the requirements file so it gets installed via pip when we install all the other requirements. Currently the shared-django-app repo has a structure like this: |- .gitignore |- __init__.py |- models.py |- pyproject.toml |- README.md |- views.py |- # other flat files |- static/ |- shared-django-app |- # static files |- templates/ |- shared-django-app |- # template files |- templatetags/ |- tests/ I've read that you can install directly from a git repo and that's what I think we would like to try to do. I added this to a pyproject.toml and put it in the shared-django-app repository: [build-system] requires = ["setuptools"] [project] name = "django-shared-app" version = "1.0.0" [packages] packages = [find_packages()] But I'm getting an error when I run pip install git+ssh://git@bitbucket.org:<org>/shared-django-app.git@dev : Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [14 … -
Django Backend - React Frontend: Trouble Creating User Profiles via POST Request
When attempting to create user profiles through a POST request from a React frontend to a Django backend, the user profile creation process isn't functioning as expected. Despite sending the necessary data to the backend, the user profile creation fails, and the expected profile isn't being created for the user. let UserProfileCreation = async (formData, userId) => { try { const response = await fetch("http://127.0.0.1:8000/user-profile/", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("authToken")}`, }, body: JSON.stringify({ user: userId, first_name: formData.name, last_name: formData.lastname, description: formData.txtname, phone_number: formData.number, // Include image fields if required: profile_picture, banner_picture }), }); if (response.ok) { return true; } else { return false; } } catch (error) { console.error("Error creating profile:", error); return false; } }; let loginUser = async (e) => { e.preventDefault(); console.log("Form Submitted!"); let response = await fetch("http://127.0.0.1:8000/api/token/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: e.target.username.value, password: e.target.password.value, }), }); let data = await response.json(); console.log(jwtDecode(data.access)); if (response.status === 200) { setAuthToken(data); setuser(jwtDecode(data.access)); localStorage.setItem("authToken", JSON.stringify(data)); const profileExists = await CheckProfile(jwtDecode(data.access).user_id); // Pass the user ID if (profileExists) { navigate("/"); } else { navigate("/continue-setup"); } } else { alert("Something went wrong"); } }; class UserProfileView(generics.CreateAPIView): queryset = UseProfile.objects.all() serializer_class … -
How to perform addition and subtraction of values from individual cells of a database table in Django?
How do you make cell G6 the sum of G5 and C6 and then subtract D6 and E6 from it? And that every lower cell of the G7, G8... should have the same scheme. I used Django Aggregation to sum the values from each column, but I can't handle adding and subtracting individual cells. -
My backend django image is not getting collected by Vue. The image also doesn't get downloaded when I try to download it using the django admin portal
This is the response I get after I try to open/download the image THIS IS THE DJANGO ADMIN Portal Please help me with my doubt as whenever I try to download/open the file it doesn't work. After this step, I am supposed to connect it with my frontend but it's not working correctly and I suspect it is because the server is not able to read it. Thank you I tried to make a few changes like adding os.environ['DJANGO_SSL_DISABLE'] = '1' in my setting.py, didn't help. I was expecting to see the image appearing when I clicked the link -
I can't use AJAX to save information about liked movies
I am new to Django and to creating web applications in general. So I don't really understand what I did wrong. I have a web application with movies. my site By clicking on the like button, the id of the liked movie should be saved. <script> document.addEventListener("DOMContentLoaded", function () { const likeButtons = document.querySelectorAll(".like-button"); likeButtons.forEach(button => { button.addEventListener("click", function () { const movieId = this.getAttribute("data-id"); if (!this.classList.contains("liked")) { this.classList.add("liked"); sendLikeToServer(movieId, true); } else { this.classList.remove("liked"); sendLikeToServer(movieId, false); } }); }); function sendLikeToServer(movieId, likeStatus) { fetch('/like-movie/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, body: JSON.stringify({ movieId: movieId, like: likeStatus }) }) .then(response => response.json()) .then(data => { console.log(data); if (data.likedMovies.length === 3) { window.location.href = "{% url 'recommendations' %}"; } }); } function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent( cookie.substring(name.length + 1) ); break; } } } return cookieValue; } }); </script> In views.py the method is prescribed: def like_movie(request): data = json.loads(request.body) movie_id = data.get('movieId') like_status = data.get('like') liked_movies …