Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use a variable where a keyword is expected
I have this problem with Django, but I feel is more of a python question: user_data = User.objects.filter(userid__startswith='Jeremy').values('mail','address') the above works and returns me exactly one line, as I know it should. This does not work: jeremy='Jeremy' user_data = User.objects.filter(userid__startswith=jeremy).values('mail','address') because manage.py runserver complains that my queryset is empty, when attempting to use it. I went all over the internet and found countless variations about using a dictionary, like this: my_kws={'userid__startswith':'Jeremy'} user_data = User.objects.filter(**mykws).values('mail','address') which do work, but when changed to: jeremy='Jeremy' my_kws={'userid__startswith':jeremy} user_data = User.objects.filter(**mykws).values('mail','address') absolutely do not. For me, at least, they end up exactly as before, with an empty querySet. Other uncountable answers propose to do: jeremy='Jeremy' user_data = User.objects.filter(f'userid__startswith={jeremy}').values('mail','address') with exactly the same result as before. FWIW, I am using python 3.10.12 -
Use external documentation for endpoint in Swagger UI
For a specific endpoint in our REST API I'd like to provide external documentation. There is an argument external_docs that can be passed to the extend_schema, but I haven't seen any example anywhere. I passed just the URL to the external documentation: @extend_schema_view( my_specific_endpoint=extend_schema( external_docs="https://documentation.example.com" ) ) class MySpecificViewSet(ModelViewSet): # class contents The clients should use the external documentation to get instructions on using it. This endpoint cannot be used through the Swagger UI and ideally the button "Try it out" should be disabled, if that's possible. Additionally, I'd like to disable the Parameters and the Response sections too. -
How to Detect Selected Text in a PDF Displayed in a Web Browser Using JavaScript or Python?
I'm working on a web application where users need to interact with PDF documents. Specifically, I need to detect the text that a user selects within a PDF displayed in their web browser. While I've managed to achieve this functionality with DOCX files,but converting PDFs to DOCX causes layout issues, with text alignment and images not being preserved properly. I've tried using PDF.js to render the PDF in the browser, but I'm struggling to detect the text that users select. My goal is to capture the selected text . Here are the main points I need help with: How can I detect the text that a user selects in a PDF rendered in the web browser? Is it possible to achieve this using JavaScript or Python, and if so, how? I've looked into PDF.js and tried some examples, but I haven't been successful in capturing the selected text. Any guidance, code snippets, or references to relevant libraries or techniques would be greatly appreciated. Additionally, I previously asked a similar question but using Python and django but haven't received any answers yet. Here is the link to that question for more context: text. -
Why am i facing "APPEND_SLASH" error in Django?
So i am creating a simple API sing Django. So every time i am getting the APPEND_SLASH issue while making a POST request on localhost:8000/cars from PM , in the body I am passing a JSON request body with one field based on the value of which the data is gonna be filtered from the sqlite DB. Also , i am unable to find "APPEND_SLASH" in my settings.py!! Below is the error message: RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to localhost:8000/cars/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. My urls.py: from django.urls import path,include from . import views urlpatterns=[ path('cars/',views.cars,name='cars'), ] My views.py: from django.shortcuts import render from django.http import HttpResponse from cars.models import car import json from django.core import serializers from django.http import JsonResponse def cars(request): if request.method=="GET": all_cars=car.objects.all() cars_data=[] for each_car in all_cars: cars_data.append({ 'name': each_car.name, 'color': each_car.color, 'fuel': each_car.fuel }) return JsonResponse(cars_data,safe=False) elif request.method == 'POST': data=json.loads(request.body) color_of_car=data.get('color_of_car') if color_of_car is not None: one_car=car.objects.filter(color=color_of_car) output=[] for each_car in one_car: output.append({ 'name': each_car.name, 'color': … -
profile pictures for users in Django
Django has the built-in form called UserCreatioonForm for creating users. It has some fields like First and Last Name, Email, etc. But is it actually possible to have a field for uploading images which will be used as profile pictures for the user? I tried to read about additional input fields on djangoproject.com/docs, but it was rather cryptic. -
Watchtower CloudWatch Integration in Django Logs: No Log Streams Created
I have a Django project with Sentry for error tracking, and logs are stored locally on the server. I want to forward these logs to CloudWatch Logs. I am using Watchtower for this integration. Here's my settings.py: ############# LOGGING ########### from boto3 import client import watchtower logger_boto3_client = client( "logs", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_S3_REGION_NAME, ) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "[{levelname}] [{asctime}] [{pathname}] [{lineno}] [{message}]", "style": "{", }, }, "filters": { "debug_filter": { "()": "server_backend.log_settings.DebugFilter", }, "info_filter": { "()": "server_backend.log_settings.InfoFilter", }, "warning_filter": { "()": "server_backend.log_settings.WarningFilter", }, "error_filter": { "()": "server_backend.log_settings.ErrorFilter", }, }, "handlers": { "debug_file": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/debug.log", "formatter": "verbose", "maxBytes": 52428800, "backupCount": 10, "filters": ["debug_filter"], }, "info_file": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/info.log", "formatter": "verbose", "maxBytes": 52428800, "backupCount": 10, "filters": ["info_filter"], }, "warning_file": { "level": "WARNING", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/warning.log", "formatter": "verbose", "maxBytes": 52428800, "backupCount": 10, "filters": ["warning_filter"], }, "error_file": { "level": "ERROR", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/error.log", "maxBytes": 52428800, "backupCount": 10, "formatter": "verbose", }, "watchtower": { "level": "DEBUG", "class": "watchtower.CloudWatchLogHandler", "boto3_client": logger_boto3_client, "log_group": "server_backend", "stream_name": "{strftime:%Y-%m-%d}", "formatter": "verbose", "create_log_group": True, "create_log_stream": True, }, }, "loggers": { "server_backend": { "handlers": ["debug_file", "info_file", "warning_file", "error_file", "watchtower"], "level": "DEBUG", "propagate": True, … -
how to handel default Django authentication in forntend
I'm working on a project, in the back-end we are using Django with Rest and for front we are using Wordpress and we want to send otp for user and if the OTP code from user is valid then login the user and save the CSRF-token and so on .. but here is my problem I didn't wanted to save the opt in a table and in chatgpt it suggested that I can save it in session or memory cash, I wanted to try the session way but I encounter a problem : after calling the /send_otp/ and getting the otp I need to call the /login/ and check if the otp is a mach, but in login it returns the otp from session None and I can access the session I saved in the send_otp this is the two functions send_otp and login : class SendOTPView(APIView): def post(self, request): serializer = OTPSerializer(data=request.data) if serializer.is_valid(): phone_number = serializer.validated_data["phone"] otp_code = randint(100000, 999999) request.session['otp_code'] = otp_code print("otp in sendOTP",request.session.get("otp_code")) otp_send(phone_number, otp_code) return Response( {"detail": "OTP sent successfully"}, status=status.HTTP_200_OK ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserLoginView(APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): stored_otp = request.session.get("otp_code") print(stored_otp) user_entered_otp = serializer.validated_data["otp"] phone_number = … -
Cpanel Cron Job not working for everyday day
Cpanel Cron jobs Images I have 3 cron jobs in my cpanel, I am hitting APIs with curl, my hourly cron job is working fine but Daily cron job is not, monthly is not get to test yet for cron: you might think there is some error with API, so heres the deal: I edited the same API and changed its time to minute, the cron job starts working started wokring When i hit the API with postman manually it wokrs also i put the curl command that i put in cron into the live terminal of ssh, it works It is so weird but I am now irritated, Any Help? -
Django trying to encrypt fields when creating database and retrieveing them in decrypted form, how can I achieve this?
I am working on a django project where I need to store data inside some columns in an encrypted format and decrypt it on the fly whenever querying the said data. I have managed to encrypt the data while storing using cryptography-Fernet. def save(self, *args, **kwargs): if isinstance(self.first_name, str): self.first_name = cipher_suite.encrypt(self.first_name.encode()) super().save(*args, **kwargs) but When I am trying to retrieve the data, I am not able to fetch it in a decrypted format, As I do not know which method to override to achieve this result. What can I do to make this work? I have tried creating a property at django model But I am unable to trigger it, as I am not aware on how to trigger a model property in django models when a queryset is being executed. This is the property in question. @property def enc_first_name(self): if self.first_name: val = cipher_suite.decrypt(self.first_name).decode() return val return self.first_name Alternate solutions I tried, because our project is on python 3.10 and django 5.0, I am unable to use django-cryptography library which would have reduced complexity of this task tremendously. Also I have been recommended to use microsoft-presidio library but that only seems to work on text data directly. I … -
How to import a folder into postman?
Shows an error "No supported files found for import." I was trying to import my django folder into postman to test api's. Firstly I tried to do it in the postman app and then i installed postman extension from the vs code, the result was same. -
Django connect to remote Postgres: '127.0.0.1 works while 'localhost' fails
I set up local port forwarding to remote server on which a Postgres db is running. ssh -v -L 127.0.0.1:5433:localhost:5432 user@server-ip I can't connect from my django local server if host is set to localhost but it works if replaced by 127.0.0.1 My django settings: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '<db_name>', 'USER': '<db_user>', 'PASSWORD': 'django', 'HOST': 'localhost', 'PORT': '5433', } } When I run server, I got error as below: Error occurred during checks: OperationalError('connection failed: :1), port 5433 failed: could not receive data from server: Connection refused\ncould not send startup packet: Connection refused') I wanted to identify if the connection issue comes from client or server side, so I tried to connect to the db by psql: psql <db_name> -U <db_user> -p 5433 -h localhost and it works !!! So I guessed it was client issue. The django server could only connect to the db only when I changed 'HOST': 'localhost' to 'HOST': '127.0.0.1' My /etc/hosts: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost 127.0.0.1 postgres 127.0.0.1 mysql 127.0.0.1 redis pg_hba.conf: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost # Added by saritasa 127.0.0.1 postgres 127.0.0.1 mysql 127.0.0.1 redis # Added by Docker Desktop # To allow the … -
Issue accessing deeply nested attributes in Django Rest Framework serializer's validate method
I'm facing an issue while trying to access deeply nested attributes within the validate method of a Django Rest Framework serializer. Here's a simplified version of my serializer: from rest_framework import serializers from myapp.models import User class YourSerializer(serializers.ModelSerializer): def validate(self, attrs): if hasattr(self.parent.instance, 'vehicle'): if hasattr(self.parent.instance.vehicle, 'engine'): if hasattr(self.parent.instance.vehicle.engine, 'fuel'): fuel_type = self.parent.instance.vehicle.engine.fuel.diesel if fuel_type: pass else: raise serializers.ValidationError("Fuel type is not available.") else: raise serializers.ValidationError("Fuel attribute is not available.") else: raise serializers.ValidationError("Engine attribute is not available.") else: raise serializers.ValidationError("Vehicle attribute is not available.") return attrs In the validate method, I'm attempting to access deeply nested attributes (vehicle.engine.fuel.diesel) of the parent instance. The thing is Model engine is created after user does ABC operations, and same applies for fuel, and diesel. When a load of people work on codebase its tough to identify if a these Models are created or not, normally getattr() and hasattr() are used, but clubbing these a lot makes code look messy. Tried static loots like mypy and pylint, they help to a certain extent but sometimes, TypeError, NoneType issues popup. Not sure how to fix these. Thank you for your help! -
Django can't find leaflet admin widget.html
I want to use LeafletGeoAdmin in the Admin pages. from leaflet.admin import LeafletGeoAdmin @admin.register(Marker) class MarkerAdmin(LeafletGeoAdmin): list_display = ("name", "location") When I try to add a marker, I get the error: TemplateDoesNotExist at /admin/my_app/marker/add/ Exception Value: leaflet/admin/widget.html Django tried loading these templates, in this order: django.template.loaders.filesystem.Loader: /home/me/my_map/.venv/lib/python3.10/site-packages/django/forms/templates/leaflet/admin/widget.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/my_map/my_map/templates/leaflet/admin/widget.html (Source does not exist) ... etc ... So it's looking for widget.html in paths of the form <many-places>/leaflet/admin/widget.html. None of the places it's looking in has it. By looking in .venv I did find it at /home/me/my_map/.venv/lib/python3.10/site-packages/leaflet/templates/leaflet/admin/widget.html instead of at site-packages/django/forms/templates/, etc. So I added that templates/ location with both absolute and relative paths to settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'my_app','templates'), '/home/me/my_map/.venv/lib/python3.10/site-packages/leaflet/templates/', os.path.join(BASE_DIR,'.venv/lib/python3.10/site-packages/leaflet/templates/') ], ... But it still gives me the same error. why does django-leaflet not know the right path, and 2) why can't Django find it at the template path I specified? -
How can I serve React Frontend and Django Backend on IIS?
Background We have an application using React.js for the frontend and Django for the backend. We are attempting to deploy this application on an Azure virtual machine with IIS. Problems Encountered Backend Accessibility: We are uncertain whether our Django server is running and how to access it. Accessing localhost only serves the frontend, raising concerns about frontend-backend communication. 404 Error on Page Refresh: When navigating to authentication/sign-in from the frontend, it works fine. However, refreshing this page results in a HTTP Error 404.0 - Not Found error. It seems IIS is looking for a physical path that doesn't exist, as the build folder contains only static files (CSS, JS, etc.). Steps Taken Created a new instance on Azure: Installed Python and other necessary packages. Configured IIS: Enabled IIS features and other relevant features. Installed SSL certificate (.pfx) using MMC to enable HTTPS support. Moved project folder to C:\inetpub\wwwroot. Configured the Python path and FastCGI path in the web.config file, placed next to the project folder. Setup Virtual Directory: Moved the build folder (static build from React) to the virtual directory. Completed all configurations for mapping, FastCGI, and static file handling. Running the Application: The frontend is served successfully when accessed … -
Django User object has no attribute user
I am trying to create some custom authentication classes to check if the request user is part of certain groups or not. However, I am getting this AttributeError: 'User' object has no attribute 'user' appear and I dont know how to resolve it. This is the file I created for my custom authentication classes: from rest_framework import permissions class IsManager(permissions.BasePermission): def has_permission(self, request, view): if request.user.user.group.filter(name='managers').exists(): return True else: return False class IsDeliveryCrew(permissions.BasePermission): def has_permission(self, request, view): if request.user.user.group.filter(name='delivery crew').exists(): return True else: return False This is me view file: from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from rest_framework.throttling import AnonRateThrottle, UserRateThrottle from django.shortcuts import get_object_or_404 from django.http import HttpResponseBadRequest from django.contrib.auth.models import Group, User from .models import Category, MenuItem, Cart, Order, OrderItem from .serializers import CategorySerialzier,MenuItemSerialzier,CartHelpSerializer, CartAddSerialzier,CartRemoveSerializer, CartSerialzier, ManagerListSerializer,OrderSerialzier,OrderItemSerializer,OrderAddSerializer, OrderItemHelperSerialzier from .permissions import IsManager, IsDeliveryCrew from datetime import date import math class CategoriesView(generics.ListCreateAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = Category.objects.all() serializer_class = CategorySerialzier permission_classes= [IsAdminUser] class MenuItemsView(generics.ListCreateAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = MenuItem.objects.all() serializer_class = MenuItemSerialzier search_fields = ['title','category__title'] ordering_fields = ['price','category'] def get_permissions(self): permission_classes = [] if self.request.method != 'GET': permission_classes = [IsAuthenticated,IsAdminUser] return [permission() for permission in permission_classes] class SingleMenuItemView(generics.RetrieveUpdateDestroyAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = MenuItem.objects.all() serializer_class … -
Filtering row with same column date value
I have a datetime field, and I want to filter the rows that has the same date value. models.py class EntryMonitoring(models.Model): student = models.ForeignKey('Student', models.DO_NOTHING) clockin = models.DateTimeField() clockout = models.DateTimeField(null=True) views.py def check_attendance(request, nid): day = EntryMonitoring.objects.filter( clockout__isnull=False, '# same value', student=nid ).annotate(...) # do something I wanted to add inside that filter query that clockin__date has the same value as clockout__date. Is that possible? If it is, what would be the right query to filter it? -
How to move submit row to the top of the Django admin panel
I have pretty large list of objects so I would like to move the "save" button in the Django admin panel to the top of the list of objects, rather than the bottom. This would be similar to the result shown in the attached image. -
Issues with File Encryption/Decryption using pycryptodome
We've recently upgraded our project from Python 2.7 and Django 1.11 to Python 3.11 and Django 3.2. In the process, we've switched from using the pycrypto library to pycryptodome for cryptographic operations. Our Django application handles file uploads and downloads with encryption and decryption as follows: File Uploads: When a user uploads a file, it gets encrypted and stored in Google Cloud Storage (GCS) with a .enc extension. File Downloads: When a user requests to download a file, Django retrieves the file from GCS, decrypts it, and then sends the decrypted file to the user. Since the migration, we've encountered issues related to the encryption and decryption process. Specifically, the files are not being correctly encrypted or decrypted, leading to corrupted downloads. Here's a brief outline of our current approach: Encryption: Using pycryptodome to encrypt files before uploading to GCS. Decryption: Using pycryptodome to decrypt files after downloading from GCS. Has anyone else faced similar issues after upgrading to Python 3.11 and Django 3.2? Any insights or solutions to ensure proper encryption and decryption with pycryptodome in this setup would be greatly appreciated. Here' my crypto.py, which handles encryption and decryption from Crypto.Cipher import AES from Crypto import Random from … -
psycopg2.errors.UndefinedTable: relation "mydjangoapp_mymodel" does not exist
I am managing a django app built by third parts. I have configured in settings.py the connection to a new db 'default': { # changed 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'waterwatch', 'USER': 'waterwatch_main', 'PASSWORD': '****', 'HOST': 'localhost', } Now I want to populate the new database with the table in my models.py, that is class WaterConsumption(models.Model): Id = models.IntegerField(primary_key=True) Suburb = models.CharField(max_length=100) NoOfSingleResProp = models.IntegerField() AvgMonthlyKL = models.IntegerField() AvgMonthlyKLPredicted = models.IntegerField() PredictionAccuracy = models.IntegerField() Month = models.CharField(max_length=50) Year = models.IntegerField() DateTime = models.DateTimeField() geom = models.PointField() def __str__(self): return self.Suburb class Meta: verbose_name_plural = 'WaterConsumption' so I run python manage.py makemigrations but I get django.db.utils.ProgrammingError: relation "waterwatchapp_waterconsumption" does not exist well... I guess that is obvious, I am actually trying to create new tables in my new database. I guess something is wrong with the migrations. so I have dropped and recreated the database, deleted all files in waterwatchapp/migrations , except __init__.py waterwatchapp/__pycache__ waterwatch/__pycache__ But as I run again python manage.py makemigrations or python manage.py migrate, I still get the same error. Why does django does not creates the tables anew? It seems to me that django is still somehow following a sort of track of what was in the database before. … -
Unable to process the input data from ModelMultipleChoiceField in Django
I've been trying to process the data captured from a simple Django Model Form, and for some reason, it isn't possible to access the group of items selected under ModelMultipleChoiceField. I'm only able to access only one item from the selected items in the form. The Model: class Student(models.Model): name = models.CharField(max_length=80) subjects = models.ManyToManyField(Subject) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name="students_of_house") The Model form: class AddStudentForm(forms.Form): name = forms.CharField(label="Full Name") house = ModelChoiceField(queryset=House.objects.all()) subjects = ModelMultipleChoiceField(queryset=Subject.objects.all()) The view function to process POST and create a Student Object.: def add_student(request): if request.method == "POST": name = request.POST["name"] house = House.objects.get(id=int(request.POST["house"])) subject_ids = request.POST["subjects"] new_student = Student(name=name, house=house) new_student.save() for sub_id in subject_ids: new_student.subjects.add(Subject.objects.get(id=int(sub_id)) new_student.save() return HttpResponseRedirect(reverse("administration:students")) context = { "add_student_form": AddStudentForm(), } return render(request, "administration/add_student.html", context) Now, I later tried using form = AddStudentForm(request.POST) and if form.is_valid(): route, which made it work successfully. But I'm having a hard time figuring out the reason why the above method isn't working. The code which worked: def add_student(request): if request.method == "POST": form = AddStudentForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] house = form.cleaned_data["house"] subject_ids = form.cleaned_data["subjects"] new_student = Student(name=name, house=house) new_student.save() for sub_id in subject_ids: new_student.subjects.add(Subject.objects.get(id=sub_id.id)) new_student.save() return HttpResponseRedirect(reverse("administration:students")) context = { "add_student_form": AddStudentForm(), } … -
Django Allauth headless Unauthorized 401 (Initial)
I'm receiving 401 when trying to reach the end point "/_allauth/browser/v1/auth/password/reset", althoug sending cookie, crsf and the key for email reseting. I'm following the flow of reseting the users password from a vuejs Frontend with this: async function sendEmailReset() { spin.value = true; try { const resp = await api.get("/api/email-reset/" + email.value); if (resp.data.status == "none") { error_message.value = "Este e-mail não existe no sistema. Faça o processo de registro novamente."; wrongCredentials.value = true; return; } else if (resp.data.status == "social") { error_message.value = "Este email foi cadastrado com uma conta social. Faça login com o Google."; wrongCredentials.value = true; return; } else { const response = await api.post( "/\_allauth/" + authClient + "/v1/auth/password/request", { email: email.value }, { headers: { "Content-Type": "application/json" }, } ); console.log(response); if (response.data.status == 200) { sentEmail.value = true; } else { error_message.value = "Ocorreu um erro ao enviar o e-mail. Verifique se o e-mail está correto."; wrongCredentials.value = true; } } } catch (error) { console.error(error); error_message.value = error.response?.data.detail || "Ocorreu um erro na conexão com o servidor. Se persistir, tente novamente mais tarde."; wrongCredentials.value = true; } finally { spin.value = false; email.value = ""; } } it works fine and send … -
Django custom admin template view problem
I changed the admin site index template in Django like this: admin.site.index_template = "admin/list-aprovals.html" but how can i send my model datas this page or can i add a custom view for this url: path('admin/', admin.site.urls), So, I want to work with the existing django admin, but I only want to change the template and see my models in this special template, but with the original admin app. Is this possible in Django? How do I solve this problem? I tried custom app but i want to use original contrib admin. -
How to add data to Django's database by the click of a button using JS
I'm trying to add this data on database when it's clicked. It updates on my website which is static. But the data in not updating on the Database. Showing list From database on index.html <ul id="myUL"> {% for name in names %} {% if name.com == True %} <li class="checked">{{name.names}}</li> {% else %} <li>{{name.names}}</li> {% endif %} {% endfor %} </ul> JavaScript code on index.html. I want to make it like if I click on the button then the the data will be added in the database. Then if i Refresh it The new task which I've implemented. It'll show. Also When the on of the item is checked it will be updated which is true or false. When I check one of the tasks it'll automatically update the database. // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value … -
Django Template Inheritance Issue: {% if %} Block Not Rendering When Extending base.html
Problem Description I'm working on a Django project where I have a form that, when submitted, calculates some results and displays them on the same page. The issue arises when I use a base template (base.html). Without using base.html, everything works perfectly, and the results are displayed correctly. However, when I extend from base.html, the content within the {% if results %}{% endif %} block in my test.html template doesn't get displayed at all. base.html Here is my base.html: <!DOCTYPE html> <html> <head> <title>{% block title %}AbiturTest{% endblock %}</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'main/css/style.css' %}"> <link rel="icon" type="image/x-icon" href="{% static 'main/img/icon.ico' %}"> <link rel="apple-touch-icon" href="{% static 'main/img/icon.png' %}"> <link rel="shortcut icon" href="{% static 'main/img/icon.ico' %}"> </head> <body> <header> <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'test' %}">Test</a></li> </ul> </nav> </header> <div class="container"> {% block content %}{% endblock %} </div> </body> </html> test.html Here is my test.html: {% extends 'main/base.html' %} {% block title %}Test - AbiturTest{% endblock %} {% block content %} <h1>Тест AbiturTest</h1> <form id="test-form" method="post"> {% csrf_token %} <ul> {% for question in questions %} <li>{{ question.text }} <div class="radio-buttons"> <input type="radio" id="q{{ question.id }}_1" class="radio-button" name="answer_{{ question.id }}" value="1" … -
aws app running django static s3 url missing colon wrong url
this is my first post and i was to highlight a problenm that i've struggled with for a whole day. While configuring my django project by recovering the static files from an s3 bucket i've ended up with a problem, the url prefixed in fron of the static resources was generating without : after the protocol, like this: <link rel="shortcut icon" type="image/png" href="https//django-examplebucketname.s3.amazonaws.com/static/images/favicon.png"> so at the css, js and all the other static resources were giving 404. in the tamplate i had: {% load static %} and the settings file instead was configured like that: WS_ACCESS_KEY_ID = "myid" AWS_SECRET_ACCESS_KEY = "mykey" AWS_STORAGE_BUCKET_NAME = "django-examplebucketname" AWS_S3_REGION_NAME = "my-region" AWS_S3_CUSTOM_DOMAIN = "django-examplebucketname.s3.amazonaws.com" AWS_S3_URL_PROTOCOL = "https" AWS_S3_USE_SSL = True AWS_S3_VERIFY = True AWS_LOCATION = "static/" STATIC_URL = "https://django-examplebucketname.s3.amazonaws.com/static/" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" but the static url was not taken in consideration and once released over apprunning the url was always missing the : (colon) after the protocol no other configurations were applied over the project. With the local setting and whitenoise was working. I've checked: the policy on the bucket --> they were ok (trying to connect directly to a resource via the bucket url was reachable) changing the static_url manually override the static …