Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please, how can I implement logging in django such that I pass the logs to a database rather than a file?
Here is my implementation //myproject/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'logger.apps.LoggerConfig', ] # Logging # https://docs.djangoproject.com/en/5.0/topics/logging/ LOGGING_CONFIG = None # Disable the automatic configuration LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'database': { 'level': 'DEBUG', 'class': 'logger.handler.DatabaseLogHandler', 'formatter': 'verbose' }, 'browser': { 'level': 'DEBUG', 'class': 'logger.handler.BrowserLogHandler', }, }, 'loggers': { 'django': { 'handlers': ['database', 'browser'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['database', 'browser'], 'level': 'ERROR', 'propagate': False, }, 'security': { 'handlers': ['database', 'browser'], 'level': 'INFO', 'propagate': False, }, }, } //myproject/logger/apps.py from django.apps import AppConfig class LoggerConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'logger' //myproject/logger/handlers.py import logging from django.utils.timezone import now import logging class DatabaseLogHandler(logging.Handler): def emit(self, record): from logger.models import LogEntry log_entry = LogEntry( level=record.levelname, message=record.getMessage(), logger_name=record.name, filepath=record.pathname, func_name=record.funcName, lineno=record.lineno ) log_entry.save() class BrowserLogHandler(logging.Handler): logs = [] def emit(self, record): log_entry = { 'logger_name': record.name, 'level': record.levelname, 'message': record.getMessage(), 'timestamp': now().isoformat() } self.logs.append(log_entry) @classmethod def get_logs(cls): logs = cls.logs[:] cls.logs.clear() return logs //myproject/logger/models.py from django.db import models from django.utils.translation import gettext_lazy as _ class LogEntry(models.Model): timestamp = models.DateTimeField(auto_now_add=True) … -
My new staging slot cannot connect to a github workflow
I just upgraded my azure web application so that I can have additional deployment slots. I want to be able to push updates from my github to the azure staging slot of my web app so that i can confirm my changes are functioning and loaded before "swapping" it to the my production slot where my domain is active. I can setup continuous deployment on my production slot but when i try to set it up under my staging slot it always gives me errors telling me my resource is not found in github actions. Does anyone have feedback or experience on this? -
How to display a select box from all possible tags in django-admin when using django-taggit?
I'm trying to display a field for tags in the Django admin panel for each post, in which you can enter the desired tag or select from all available tags. It is not possible to select from all available tags. Tell me how exactly this should be implemented? from django.contrib import admin from django.db import models from taggit.forms import TagWidget from .models import Post, Comment @admin.register(Post) class PostAdmin(admin.ModelAdmin): fields = ('title', 'slug', 'author', 'body', 'publish', 'status', 'tags') list_filter = ('status', 'created', 'publish', 'author') list_display = ('title', 'slug', 'author', 'publish', 'status', 'get_tags') prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) formfield_overrides = { models.ManyToManyField: {'widget': TagWidget}, } def get_tags(self, obj): return ", ".join(o for o in obj.tags.names()) -
user profile management project in django
Part 1 : User Profile Management Robust user profile management system facilitating the creation and customization of personal profiles, including biographical information, skill sets, and contact details. Part 2 : Portfolio Customization Intuitive interfaces enabling users to tailor their portfolios with personalized content, including project showcases, work experience, education, and certifications. Part 3 : Project Showcase A visually appealing and interactive presentation of past projects, complete with detailed descriptions, images, and relevant links to provide visitors with a comprehensive understanding of the showcased work can any one guide me to do this project..I am done with part 1..I get input from user and make it a crud operation..But after some time i got that the logined user can only create one portfoilo..I didnt get how to connect three tables and their updations can any one guide me..I was stuck in part 2 and part 3 of the project in django -
why django resframework login view throwing error?
I am developing an OTP based authentication model. below are the back-end and front-end logic serializers.py class LoginSerializer(serializers.Serializer): email = serializers.EmailField() otp = serializers.CharField() def validate(self, data): email = data.get('email') otp = data.get('otp') # Logging the initial validation step api_log(msg="Starting validation") # Check if email exists try: user = User.objects.get(email=email) except User.DoesNotExist: raise serializers.ValidationError( { "email": "Email does not exist." } ) if user.otp != otp: raise serializers.ValidationError( { "otp": "OTP is invalid or expired." } ) if User.otp_expiry and User.otp_expiry < timezone.now(): raise serializers.ValidationError( { "otp": "OTP is expired." } ) # Attach user to validated data data['user'] = User return data views.py class LoginView(KnoxLoginView): # @csrf_exempt def post(self, request, *args, **kwargs): serializer = LoginSerializer(data=request.data) api_log(msg=f"login view serializers : {serializer}") if serializer.is_valid(): user = serializer.validated_data['user'] api_log(msg=f"login view USER : {user}") # Invalidate the OTP user.otp = None user.otp_expiry = None user.save() # Create auth token _, token = AuthToken.objects.create(user) api_log(msg=f"login view TOKEN : {token}") return Response({'token': token}, status=status.HTTP_200_OK) else: return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form id="login-form"> {% csrf_token %} <div class="form-group"> <h1>Login</h1> <p>Please enter your email and OTP to login.</p> <hr> <label for="email"><b>Email</b></label> <input type="text" … -
How to Assign Existing Contacts to a Task Using Postman in Django Rest Framework Without Duplicating Email
I am currently working on a project using Django Rest Framework and Postman. My objective is to assign existing contacts to a task. However, when I make a POST request via Postman, I receive the error: "contact with this email already exists" The email field in my Contact model is defined as models.EmailField(unique=True), as I need to ensure that each email is unique across all contacts. When I attempt to assign an existing contact to a task using a POST request, I receive the aforementioned error. Here's the relevant part of my code: http://127.0.0.1:8000/tasks/ { "id": null, "title": "Postman", "description": "Postman", "dueTo": "2024-06-12T12:04:28Z", "created": "2024-06-12T12:04:31Z", "updated": "2024-06-12T12:04:34Z", "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [ { "id": null, "description": "Postman", "is_done": false } ], "contacts": [ { "id": 1, "email": "max@mueller.com", "name": "Max Mueller", "phone_number": "123456789", "avatar_color": "#abcdef" } ] } models.py class Contact(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) name = models.CharField(max_length=50) phone_number = models.CharField(max_length=30) avatar_color = models.CharField(max_length=7) def __str__(self): return f"{self.name}" serialzers.py class ContactSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Contact fields = ['id', 'email', 'name', 'phone_number', 'avatar_color'] models.py class Task(models.Model): id = models.AutoField(primary_key=True) title = models.TextField() description = models.TextField() dueTo = models.DateTimeField() created = models.DateTimeField() updated = models.DateTimeField() priority … -
My form is automatically being submitted in django whenever I open the link
Well I am creating a admin approval view for an account upgradation but it is not working as I expected. I wanted to get a form and then depending upon the data the form is either approved or rejected. I have created the form and everything else but the form is automatically submitting without even rendering along with all that it is getting approved too. Help me please. Model: class CabbieRequest(models.Model): user = models.ForeignKey(Passenger, on_delete=models.CASCADE) vehicle = models.ForeignKey('Rides.Vehicle', on_delete=models.PROTECT) requested_at = models.DateTimeField(auto_now_add=True) is_approved = models.BooleanField(default=False) approved_at = models.DateTimeField(null=True, blank=True) def approve(self): self.is_approved = True self.approved_at = timezone.now() Cabbie.objects.create( username=self.user.username, email=self.user.email, phone=self.user.phone, image=self.user.image, vehicle=self.vehicle, stars=0.0, password=self.user.password ) self.save() def __str__(self): return f'Request by: {self.user.username}' View: @login_required def request_cabbie_upgrade(request): if request.method == 'POST': vehicle_form = VehicleForm(request.POST) if vehicle_form.is_valid(): vehicle = vehicle_form.save(commit=False) vehicle.save() cabbie_request = CabbieRequest(user=request.user, vehicle=vehicle) cabbie_request.save() return redirect('PassengerDashboard') else: vehicle_form = VehicleForm() return render(request, 'users/cabbie_request.html', {'vehicle_form': vehicle_form, 'cabbie': request.user}) Form: class CabbieRequestForm(forms.Form): approve = forms.BooleanField(required=False) reject = forms.BooleanField(required=False) Template: {% extends "base.html" %} {% load static %} {% block title %} <title>Manage Cabbie Request</title> {% endblock title %} {% block body %} <div class="container mt-5 pt-5 manage-request-container"> <div class="row"> <div class="col-md-12"> <h2>Manage Cabbie Request</h2> <div class="card"> <div class="card-body"> <p><strong>Username:</strong> {{ user.username … -
Issue with Toggling between New Themes
I'm encountering an issue with a custom Theme Installation in my Django project using v. 4.2.13 and Python v. 3.9.7. In the default Admin side, there is a Moon icon for toggling the Themes (i.e. b/w Light and Dark and Auto). I want to add a Grey theme as my default with a new icon. So there are total 4 icons for themes now - Grey, Light , Dark & Auto. For implementing this, I added a new icon for the Grey theme and the icon is now not visible in the Admin panel (only the default 3 are shown) and the toggling between themes is not working. Below are the screenshots of the code for installing themes with their respective icons. Please also note my teammate has been working on Django 5.0 for making his previous project commits in Github. We wanted to test what can happen to the same functionality if team members work on different versions since we're assuming Git essentially stores all files as basic text files with version control. I am not sure if this has anything to do with my problem. Kindly help. Screenshot 1 - The Admin panel moon icon for theme toggle … -
Globally JSON-serializing UUIDs and other types with psycopg2 and django
I'm developing an application with Django 4.2.10. I am running a postgres database and use psycopg2. In my application, I am working with nested dictionaries (coming out of Django ninja/pydantic schemas) and I would like to write these to JSONField django fields. However, they contain UUID's which results in the following error: TypeError: Object of type UUID is not JSON serializable To resolve this problem, I really prefer a "global" hook/adapter that convinces psycopg2 to properly serialize UUID's and other types so that I don't have to worry about it in all the places where I write this data into the database. It should work for direct/raw queries but also via the Django ORM. I found this JSON Adaptation section in the psycopg2 docs. Note You can use register_adapter() to adapt any Python dictionary to JSON, either registering Json or any subclass or factory creating a compatible adapter: psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json) This setting is global though, so it is not compatible with similar adapters such as the one registered by register_hstore(). Any other object supported by JSON can be registered the same way, but this will clobber the default adaptation rule, so be careful to unwanted side effects. So my thought … -
Session Timeout on User side in Django
I am trying add a session timeout in my Django project by using Django's in-built session middleware. I have implemented session timeout on my project using the Views method I have come across for this purpose and it is working on my Admin side, but in my User side, the redirection that I given not working (i.e. I need to log out the user and get back to the signin page after session expires). My django version : 5.0.2 My python version: 3.12.2 Now it is taking the time and that page will expire but it will not redirect to the signin page. How can I solve this issue? What are some other approaches we can use for implementing Sessions on Admin & User sides both redirecting to the Signup page and persisting the last page worked on upon logging back in ?settings.pymiddilewareViews.pyurls.py -
Hi, i need help passing my cv2 yolov8s video feed to a django application i got for my project
Im new to neural network development i got pretrained YOLO8s model and trained it on my custom dataset, made a python class, using cv2 to display the results now i need help passing my cv2 yolov8s video feed to a django application i got for my project, how do i do that? ''' from ultralytics import YOLO from pathlib import Path import cv2, onnx, onnxoptimizer,numpy,onnxruntime import torch.onnx import torchvision.models as models from database.db import * from pprint import pprint as pt class Main_field: def __init__(self, model, size, source, conf_): self.model = self.load_model(model) self.size = size self.source = source self.conf_ = conf_ def __call__(self): self.process_video() def load_model(self, model): model.fuse() return model def process_video(self): cap = cv2.VideoCapture(self.source) while True: ret, frame = cap.read() if not ret: break results = self.model.predict(frame, conf=self.conf_, imgsz=self.size) masks_dict=[result.names for result in results][0] xyxys=[result.boxes.cpu().numpy().xyxy for result in results][0] #xyxy mask_ids=[result.boxes.cpu().numpy().cls.astype(int).tolist() for result in results][0] masks=[masks_dict[itr] for itr in mask_ids] db_output=[check_(local_list,str(itr)) for itr in mask_ids if itr] video_outp=cv2.imshow("_________", results[0].plot()) pt(mask_ids) if cv2.waitKey(1) & 0xFF == ord('q'): break def __del__(): cap.release() cv2.destroyAllWindows() def init_model(path: str) -> any: return YOLO(path) ''' looking for examples on how can i pass constant video feed to my web page -
Problem when trying to generate PDF files within Django with libreoffice
I have a Django application based on the 3.10.11-alpine3.16 image that runs in docker container. When I check during the build if a sample PDF is generated, this will succeed, and I see that when running with root it is okay. The problem is that when I try to issue the same command in the running container's terminal, I got an error and I don't know why. In my dockerfile I have the commands to isntall the libreoffice: RUN apk add --no-cache xmlsec xmlsec-dev libreoffice libreoffice-writer libreoffice-calc libreoffice-impress libreoffice-base ttf-dejavu unzip wget curl openjdk11-jre This commands runs perfectly during build in the name of the root user: RUN soffice --headless --convert-to pdf --outdir /vol/logs /vol/logs/word_sample_01.docx If I try to run the same command when I logged into the docker's terminal, so for example: /usr/bin/soffice --headless --convert-to pdf --outdir /vol/logs/t/ /vol/logs/word_sample_01.docx I get this error: "Unspecified Application Error" I assume it is related to some permissions, but I can't figure it out which one is missing... Any hints? -
After scheduling a new task, previously scheduled tasks are not getting executed by Celery Beat (Django)
I have a Django (4.2.2) app running with Python (3.10.12), Celery (5.4.0), Celery Beat (2.6.0), Django Celery Results (2.5.1), Redis and Postgres. Here is my celery configuration: CELERY_BROKER_URL = "redis://localhost:6379/3" from __future__ import absolute_import, unicode_literals from celery import Celery from django.conf import settings import os import django # Set the DJANGO_SETTINGS_MODULE before calling django.setup() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auctopus.settings') django.setup() # Initialize Celery app = Celery('proj') app.conf.enable_utc = False app.conf.broker_connection_retry_on_startup = True app.conf.task_serializer = 'json' app.conf.accept_content = ['application/json'] app.conf.result_serializer = 'json' app.conf.timezone = 'Asia/Kolkata' app.conf.cache_backend = 'default' app.conf.database_engine_options = {'echo': True} app.conf.result_backend = 'django-db' app.conf.result_expires = 3600 app.conf.task_time_limit = 1000 app.conf.task_default_queue ='default' app.conf.worker_concurrency = 6 app.config_from_object(settings, namespace='CELERY') # Autodiscover tasks from installed apps app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler' After Django application starts, it creates several schedulers automatically such as internet_status_check, system_resource_check, etc. using IntervalSchedule. At first, it runs smoothly, but as soon as I create any new scheduler be it an IntervalSchedule or CrontabSchedule, previously running schedulers stop execution. I get a message in celery beat terminal also saying DatabaseScheduler: Schedule changed. After this message it does not send any task for execution even if tasks are available for execution which can be seen from Django admin panel. I tried changing broker to … -
How to integrate different user types in djando UserModel?
I have a question regarding the user model in django. My project is to realize an area management system. The following entities have already been modeled: Building Area Area equipment (e.g. which furniture etc) SpaceUser (assignment between space and user) SpaceRequirement (request from a user) Users (those who were, are and will be on the space) Supervisor (user who is responsible for certain areas or buildings) TypeOfUse (e.g. office, laboratory, etc.) Organization (organizational affiliation to team/department etc) Landlord As a special case, the management of workshop spaces that are to be bookable at short notice is managed in the following entities: WorkshopSpace (space x in building y) WorkshopSpaceRequirement (request from a user) The attributes of the entities are: Supervisor firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) organisation = models.ForeignKey('Organization', verbose_name='Organization', on_delete=models.CASCADE) email = models.EmailField(verbose_name='Email') phone_number = models.CharField(max_length=20) Users: organisation = models.ForeignKey('Organization', verbose_name='Organization', on_delete=models.CASCADE) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) mgmt_level = models.CharField(max_length=10, choices=CATEGORY_CHOICES, default=E4, verbose_name='Level') cost_center = models.CharField(max_length=50, blank=True) number_employees = models.IntegerField(default=0, verbose_name='Number of employees') number_workstations = models.IntegerField(default=0, verbose_name='Number of workstations') superior = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) comment = models.TextField(blank=True) Unfortunately, I made the mistake of implementing the models without taking the django user model into account. I would now like … -
requirements.txt file packages version upgrade in django project
While I'm upgrading the packages in my django project and run locally it won't raise any error but when I am pushing the code to dev environment, it shows me internal server error I'm not sure is it because of the upgradation or is it because of the CI CD pipeline. I upgrade the django version from 3.2 to 4 2.3 and some other packages and all the thing are working fine in local but not in dev environment -
payments import from python_flutterwave not working.... python 3.12.4
This is the inport i have in my code from python_flutterwave import payment But i am getting an error: ImportError: cannot import name 'payment' from 'python_flutterwave' (C:\Users\HP\Downloads\Compressed\STechnologies-Suite\STech-Agent-Suite\env\Lib\site-packages\python_flutterwave_init_.py). How is this possible yet according to the docs, it should be working just fine. -
ValueError on autofield on my Django Project
I'm trying to make a music streaming website using Django. I have this error when i use the terminal command migrate: ValueError: Field 'song_id' expected a number but got ''. I don't understand where "song_id" take a value that is not a number. How can i fix it? this is my views.py: def myPlaylist(request, id): user = request.user if user.is_authenticated: # Extracting Playlists of the Authenticated User myPlaylists = list(Playlist.objects.filter(user=user)) if user.is_authenticated: if request.method == "POST": song_id = request.POST["music_id"] playlist = Playlist.objects.filter(playlist_id=id).first() if song_id in playlist.music_ids: playlist.music_ids.remove(song_id) playlist.plays -= 1 playlist.save() message = "Successfull" print(message) return HttpResponse(json.dumps({'message': message})) else: images = os.listdir("music_app/static/PlaylistImages") print(images) randomImagePath = random.choice(images) randomImagePath = "PlaylistImages/" + randomImagePath print(randomImagePath) currPlaylist = Playlist.objects.filter(playlist_id=id).first() music_ids = currPlaylist.music_ids playlistSongs = [] recommendedSingers = [] for music_id in music_ids: song = Song.objects.filter(song_id=music_id).first() random.shuffle(recommendedSingers) recommendedSingers = list(set(recommendedSingers))[:6] playlistSongs.append(song) return render(request, "myPlaylist.html", {'playlistInfo': currPlaylist, 'playlistSongs': playlistSongs, 'myPlaylists': myPlaylists, 'recommendedSingers': recommendedSingers, 'randomImagePath': randomImagePath}) def addSongToPlaylist(request): user = request.user if user.is_authenticated: try: data = request.POST['data'] ids = data.split("|") song_id = ids[0][2:] playlist_id = ids[1][2:] print(ids[0][2:], ids[1][2:]) currPlaylist = Playlist.objects.filter(playlist_id=playlist_id).first() if song_id not in currPlaylist.music_ids: currPlaylist.music_ids.append(song_id) currPlaylist.plays = len(currPlaylist.music_ids) currPlaylist.save() return HttpResponse("Successfull") except: return redirect("/") # return redirect("/") else: return redirect("/") def likesong(request): myPlaylists = [] … -
I continuously receive `Invalid HTTP_HOST header` error email
I am using Django==4.1.2. I deployed my site using Docker on an Ubuntu server, and I am continuously receiving 'Invalid HTTP_HOST header' emails. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'ad608a31b0be:8000'. You may need to add 'ad608a31b0be' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www'. You may need to add 'www' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'api.ipify.org'. You may need to add 'api.ipify.org' to ALLOWED_HOSTS. Here is my Docker file code FROM python:3.9 as build-python RUN apt-get -y update \ && apt-get install -y gettext \ # Cleanup apt cache && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements.txt /app/ WORKDIR /app RUN pip install -r requirements.txt RUN pip install --upgrade pip ### Final image FROM python:3.9-slim RUN groupadd -r tgcl && useradd -r -g tgcl tgcl RUN mkdir -p /app/media /app/static \ && chown -R tgcl:tgcl /app/ COPY . /app WORKDIR /app EXPOSE 8000 CMD ["gunicorn", "--bind", ":8000", "--workers", "4", "tgcl.asgi:application"] Here is my Django Settings ALLOWED_HOSTS = ['app.thegoodcontractorslist.com', 'www.thegoodcontractorslist.com'] CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", "http://localhost:3000", "http://dev.thegoodcontractorslist.com", ] CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = … -
Updating a Foreign Key in Django Rest Framework
these are my models in DRF: class Course(models.Model): title = models.CharField(max_length=100, unique=True) class Prerequisite(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_prerequisite") title = models.CharField(max_length=75) and my serializers: class CourseSerializer(serializers.ModelSerializer): prerequisite = serializers.SerializerMethodField() class Meta: model = models.Course fields = "__all__" def get_prerequisite(self, obj): serializer = PrerequisiteSerializer(obj.course_prerequisite.all(), many=True) return serializer.data class PrerequisiteSerializer(serializers.ModelSerializer): class Meta: model = models.Prerequisite fields = "__all__" and my view to retrieve a course: def retrieve(self, request, pk=None): course = get_object_or_404(Course, slug=pk) serializer = serializers.CourseSerializer(instance=course) return Response(serializer.data, status=status.HTTP_200_OK) now my question is imagine i did send a request to my api to retrieve a course with pk of 18 like this: { "results": [ { "id": 18, 'title': 'learn python in 30 days' "prerequisite": [ { "id": 1, "title": "Introduction", "course": 18 }, ], } ] } and now i want update the prerequisite with id of 1 what code should i add to my update view in CourseViewSet, i know i can create another view for prerequisites, but i want to do it in this way exactly like when you add TabularInLine in Django`s default admin panel when you can update and change a foreignkey! -
Removing {{ choice.tag }} in Django Template Breaks JavaScript Update Function for Radio Button Selection
In my Django application, I have a form with radio buttons for selecting the number of meals per week. The form also includes checkboxes for meal preferences. I have initialized a preselected value for these fields in my form. I use JavaScript to dynamically update a summary section based on preselected selections when page loads. The radio buttons for meals_per_week are generated by Django and included in the HTML template. If I remove {{ choice.tag }}, the updateSummary function no longer receives the selected value for meals_per_week. How can I fix this issue while still removing {{ choice.tag }}? Here is the relevant part of my HTML template: {% for choice in form.meals_per_week %} <div class="flex-fill mx-1"> <div class="card mb-4 custom-card" data-input-id="{{ choice.id_for_label }}"> <div class="card-body text-center"> <input type="radio" class="hidden-input" id="{{ choice.id_for_label }}" name="{{ choice.name }}" value="{{ choice.choice_value }}" {% if choice.is_checked %}checked{% endif %}> {{ choice.tag }} <label class="form-check-label d-block" for="{{ choice.id_for_label }}"> {{ choice.choice_label }} </label> </div> </div> </div> {% endfor %} And here is my JavaScript function that updates the summary: async function updateSummary() { const mealsPerWeek = **parseInt(document.querySelector('input[name="meals_per_week"]:checked').value);** const mealPreferences = Array.from(document.querySelectorAll('input[name="meal_preference_type"]:checked')).map(el => el.value); let response = await fetch(`/get_price?meals_per_week=${mealsPerWeek}`); let data = await response.json(); const pricePerServing … -
Django,Docker caching previsouly setup email in he settings.py
I have changed my backend email when I run in docker compose it uses the previous email thus an error but when i run in manage.py runserver mode there is no error. I want when i run in docker mode for it to read the new email that i have setup -
Calculating amount when saving in django admin
I am trying to calculate the total amount of a sale before saving it in the Django admin site. Sales data model Inventory data model The SaleItem is a through table to keep track of the quantity of each item sold in the sale. How do I calculate the total price of each item sold? enter image description here I've tried declaring a method called save to calculate the price of the items sold when saving the entry in the django admin, however im getting errors for trying to perform an operation on deferred attribute. -
Django GET request a page with a button
I have a django view with html template with a form and a few buttons. When one of the buttons is pressed it sends a get request with a query param and depending on this param I render the page again but with different json paramethers. However I can't return the webpage with a second return. This is the important code of the view for the question. I also tried this without return, but it doesn't work either. I tried using JsonResponce, but no success: def card(request): cur_rk = 0 if request.method == 'GET': if request.GET.get('C', '') == '-1': q1 = "SELECT MAX(RK) AS L_RK FROM B_DATA;" with connection.cursor() as cursor: cursor.execute(q1) val = cursor.fetchall() cur_rk = val[0][0] return render(request, "card.html", get_db_data(cur_rk)) return render(request, "card.html", get_db_data(cur_rk)) Here is the html code if it might help you: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create new card</title> </head> <body> <div class = "enter_data"> <form action = "" method="POST">{% csrf_token %} <div class = "base"> <h2>Базови данни</h2> <input type="number" class="field" placeholder="Enter RK" value = {{RK}} name="RK"> <input type="text" class="field" placeholder="Enter RN" value = {{RN}} name="RN"> <input type="text" class="field" placeholder="Enter Marka" value = {{Marka}} name="Marka"> <input type="text" class="field" placeholder="Enter … -
Django: Problem rendering and downloading HTML in PDF format, styles and resources are not applied correctly
I am trying to generate a PDF with data previously entered in Django, the base of the PDF is with HTML, when creating the HTML it is rendered in order and as I want when viewing it with the ""Live Preview" extension in Visual Studio Code, but when transform it to PDF in my project, it is generated badly and messy (I'm sorry if I describe myself badly, it's the first time I use this platform D:)The idea is that it looks something like this: HTML, but when you download the PDF it looks like this: Bad PDF As a reference to make the PDF functionality I used this video: https://www.youtube.com/watch?v=J3MuH6xaDjI, this is HTML that I am using to generate the PDF: <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cotización - SOLUPLAST</title> <style> body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; } .container { max-width: 800px; margin: 0 auto; background-color: #fff; padding: 20px; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } .header { display: flex; justify-content: left; align-items: flex-start; } .logo { order: -1; } .header img { position: absolute; max-width: 120px; } .header .info { margin-top: 90px; text-align: left; … -
How can I use Google Cloud Storage and Local folders together using Django?
I have a Django app with my images on Google Cloud Storage, but I want to use just one image on the local folders This is my code: Settings.py GS_CREDENTIALS = service_account.Credentials.from_service_account_info(credentials_dict) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_PROJECT_ID = 'projectid' GS_BUCKET_NAME = 'bucketname' STATICFILES_STORAGE='storages.backends.gcloud.GoogleCloudStorage' HTML: <img src="{% static 'img/testimg.png' %}" alt=""> I want to search just for one image, how can I do this? I tried removing Staticfiles_storage line, then django searched all the images on the local folders, instead of just one