Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest-frame-work user_id related "violates not-null constraint"
I have this error jango.db.utils.IntegrityError: null value in column "user_id" of relation "defapp_actionlog" violates not-null constraint DETAIL: Failing row contains (13, "{\"action\":\"push\"}", 2024-10-21 06:11:30.43758+00, 2024-10-21 06:11:30.43759+00, null). What I want to do is push the actionlog from javascript and set the login user to model. I set the CustomUser object to user row, however it still requies user_id? my viewset,model,serializer is like this below. class ActionLogViewSet(viewsets.ModelViewSet): queryset = m.ActionLog.objects.all() serializer_class = s.ActionLogSerializer def perform_create(self, serializer): obj = serializer.save() return obj def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) request.data._mutable = True request.data['user'] = m.CustomUser.objects.get(id=request.user.id) try: serializer.is_valid(raise_exception=True) except Exception as e: logger.info(e) self.perform_create(serializer) return Response(serializer.data) class ActionLog(models.Model): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='action_user') detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ActionLogSerializer(ModelSerializer): id = serializers.IntegerField(read_only=True) user = CustomUserSerializer(read_only=True,source="actionlog_user") detail = serializers.CharField() class Meta: model = m.ActionLog fields = ('id','user','detail') -
Data from forms not saved in database (Django)
The information I enter on my Website when I want to create a new quiz is only partially saved, the data for the Quiz model is saved in my database, but the Questions with Answers are not saved in the database when creating a quiz. Could this be a problem with the routes? Because the Quiz model is in quizes models.py, and the Answers and Questions are in questions models.py [20/Oct/2024 18:57:06] "GET / HTTP/1.1" 200 15893 [20/Oct/2024 18:57:06] "GET /static/css/style.css HTTP/1.1" 404 1966 [20/Oct/2024 18:57:06] "GET /static/js/script.js HTTP/1.1" 404 1963 [20/Oct/2024 18:57:06] "GET /favicon.ico/ HTTP/1.1" 204 0 [20/Oct/2024 18:57:06] "GET /add_quiz HTTP/1.1" 200 26109 [20/Oct/2024 18:57:06] "GET /static/js/script.js HTTP/1.1" 404 1963 [20/Oct/2024 18:57:06] "GET /static/css/style.css HTTP/1.1" 404 1966 [20/Oct/2024 18:57:07] "GET /favicon.ico/ HTTP/1.1" 204 0 [] [20/Oct/2024 18:57:25] "POST /add_quiz HTTP/1.1" 302 0 [20/Oct/2024 18:57:25] "GET / HTTP/1.1" 200 16290 [20/Oct/2024 18:57:25] "GET /static/js/script.js HTTP/1.1" 404 1963 [20/Oct/2024 18:57:25] "GET /static/css/style.css HTTP/1.1" 404 1966 [20/Oct/2024 18:57:25] "GET /favicon.ico/ HTTP/1.1" 204 0 also console returns me empty list Earlier python console return [{'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {}] but it fixed when I hide management_form **Attach my code below** **add_quiz.html** … -
Product Screen is not showing up product on React, Django code
Im writing a shop using React + Django. After using Redux , the Product screen is giving an error. Request failed with status code 500 [enter image description here][1] enter image description here This is the error which i wrote in the codeblock. However, it should look like this when i choose a product: enter image description here The HomeScreen looks like this: enter image description here My code blocks: ProductActions: ` import axios from 'axios' import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL, PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL, } from '../constants/productConstants' export const listProducts = () => async(dispatch) => { try { dispatch({type:PRODUCT_LIST_REQUEST}) const {data} = await axios.get('/api/products/') dispatch({ type:PRODUCT_LIST_SUCCESS, payload:data }) } catch (error) { dispatch({ type:PRODUCT_LIST_FAIL, payload:error.response && error.response.data.message ? error.response.data.message : error.message, }) } } export const listProductDetails = (id) => async(dispatch) => { try { dispatch({type:PRODUCT_DETAILS_REQUEST}) const { data } = await axios.get('/api/products/${id}') dispatch({ type:PRODUCT_DETAILS_SUCCESS, payload:data }) } catch (error) { dispatch({ type:PRODUCT_DETAILS_FAIL, payload:error.response && error.response.data.message ? error.response.data.message : error.message, }) } } ``` **ProductReducers:** ``` import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL, PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL, } from '../constants/productConstants' export const productListReducer = (state = { products: [] },action ) => { switch(action.type) { case PRODUCT_LIST_REQUEST: return {loading: true,products: [] } case … -
Using OpenCV cv2.selectROI in Django raises error libc++abi.dylib: terminating with uncaught exception of type NSException
Using OpenCV in a Django app is causing the server to shutdown with following error: libc++abi.dylib: terminating with uncaught exception of type NSException Goal: Select ROI from the displayed image in browser What I am trying: Select an image (using cv2.imread()) and display in the browser <-- Working Select ROI using r = cv2.selectROI(...) <-- At this step the above error happens Using the code in Python shell works. But when included in Django views.py I am getting the error. What I am trying to find: Is it possible to use cv2.selectROI in Django? What are the basic requirement to accomplish what I am trying? -
How to Delete an Annotation Using Wagtail Review and Annotator.js on Button Click?
I am working with both Wagtail Review and Annotator.js in my project. I want to add a delete button (an "X" inside a red circle) to annotations, and when clicked, it should delete the corresponding annotation. I have added the delete button inside the annotation's controls, but I am struggling to properly trigger the deletion. What I have so far: I am using Annotator.js to create and manage annotations. The annotations appear on hover over the parent element (annotator-outer annotator-viewer). The delete button is injected dynamically inside the .annotator-controls span when the annotation becomes visible. I am trying to use the click event to trigger the annotation deletion, but I am not sure how to properly call the Annotator.js delete function or if I am handling the interaction correctly within Wagtail Review. Here’s the current approach I have: When the annotation parent (.annotator-outer.annotator-viewer) is hovered, I dynamically add the "X" delete button inside .annotator-controls. I attach a click event listener to the delete button. I expect the click to trigger the annotation deletion using Annotator.js. Code snippet: document.addEventListener('DOMContentLoaded', (event) => { function deleteAnnotation() { console.log('Delete function triggered!'); // Assuming annotator.js method is accessible to delete the annotation if (window.annotator && … -
Can anyone show me how to make a proper login system for my django application?
I need help building a proper login system for my homework in my django class. I am supposed to build an app that users can login in token based authentication and can post a destination and review it, but I'm stuck in the login section. I've manage to build the register systems correctly, but now I need to help with logging in. This is my login view I have. It keeps throwing a "NOT NULL constraint failed:" error so I have no idea what I'm doing wrong def login(request: HttpRequest): if request.method == "POST": email = request.POST.get('email') password_hash = request.POST.get('password') hasher = hashlib.sha256() hasher.update(bytes(password_hash, "UTF-8")) password_hash = hasher.hexdigest() token = "" letters = string.ascii_lowercase for _ in range(32): token = "".join(random.choice(letters) for _ in range(32)) session_token = Session.objects.create(token=token) response = HttpResponse("Cookie Set") try: user = User.objects.get(email=email, password_hash=password_hash) if user.check_password(password_hash): response = redirect("/") response.set_cookie('token', token) return response else: return HttpResponse("Invalid password") except User.DoesNotExist: return Http404({"Invalid email"}) return render(request, "destination/login.html") Here are my models from django.db import models import hashlib class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() email = models.EmailField(unique=True) password_hash = models.TextField() def check_password(self, hashed_password): hasher = hashlib.sha256() hasher.update(bytes(self.password_hash, "UTF-8")) hashed_password = hasher.hexdigest() return self.password_hash == hashed_password class Session(models.Model): id … -
Periodic Task Not Execute With Celery Beat
when beat and worker is run then the periodic task is being created in Django Celery Beat, but it does not execute when the time interval is completed. This task is not executed : 'task': 'stripeapp.tasks.create_google_sheet_with_payments_task', Commented 2 hours ago Tasks.py from celery import shared_task from django_celery_beat.models import PeriodicTask, IntervalSchedule import json from .models import TaskSchedule from datetime import timedelta from .stripe_to_sheet_saving import create_google_sheet_with_payments from django.utils import timezone @shared_task def schedule_automated_tasks(): print("Scheduling automated tasks.") # Log all existing periodic tasks for debugging existing_tasks = PeriodicTask.objects.all() for task in existing_tasks: print(task.name, task.task, task.interval, task.expires) # Get tasks from TaskSchedule model where status is 'running' running_tasks = TaskSchedule.objects.filter(status='running') for task_schedule in running_tasks: print(f"Found task schedule: {task_schedule}") task = task_schedule.task frequency = task.stripe_source.run_frequency if task.stripe_source else None occurrence = task.stripe_source.occurence if task.stripe_source else None end_date = task_schedule.end_date # Determine the interval based on frequency interval = get_interval_from_frequency(frequency) if interval is None: print(f"Invalid frequency: {frequency} for task {task.id}. Skipping.") continue # Invalid frequency, skip # Check if the task should be marked as complete running_count = TaskSchedule.objects.filter(task=task, status='running').count() if occurrence is not None and end_date is None and running_count >= occurrence: task_schedule.status = 'complete' # Update status to complete task_schedule.save() print(f"Task {task.id} marked as … -
Problem with testing Messages in Django 5 CreateView
I am writing unit tests of ebook catalog applications in Django 5. The book creation page uses the built-in CreateView. The class code looks like this: class BookCreate(SuccessMessageMixin, PermissionRequiredMixin, CreateView): model = Book fields = ['title', 'author', 'genre', 'publisher', 'pages', 'cover', 'summary'] template_name = 'books/add_book.html' permission_required = 'catalog.add_book' permission_denied_message = 'Not enough permissions to add a book' success_message = 'Book successfully added' success_url = reverse_lazy('add-book') It works as follows: the user fills in the book data, clicks the submit button, then the page is redirected to the same page, plus the page displays the message specified in the success_message attribute of the class For testing, I use the MessagesTestMixin as described in the Django documentation. Here is the unit test code: class TestBookCreateView(MessagesTestMixin, TestCase): @classmethod def setUpTestData(cls): cls.test_user = User.objects.create_user( email='john123@gmail.com', username='John', password='Fiesta123' ) cls.add_book_permission = Permission.objects.get(codename='add_book') def setUp(self): login = self.client.login(username='Ivan', password='Fiesta123') self.test_user.user_permissions.set([self.add_book_permission]) def test_if_view_success_message_attached(self): author = Author.objects.create( first_name='Charles', last_name='Dickens' ) genre = Genre.objects.create( genre='Novel' ) book_data = { 'title': 'Great Expectations', 'author': author, 'genre': genre } response = self.client.post(reverse('add-book'), data=book_data, follow=True) self.assertMessages(response, 'Book successfully added') The test fails, I see an empty list in the results instead of a message. However, in the application, the message is successfully … -
Vercel is deploying my django website without css attachement
I deployed my Django website on Vercel successfully, yet it is hosted without static files, mainly; the CSS file. Here is my files structure: And here is my form.html code: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form</title> <link rel="stylesheet" href="{% static 'client/style.css'%}"> <style> @media (max-width: 768px) { .container { width: 100%; padding: 10px; } } </style> </head> <body> <div class="content"> <div class="container"> <div class="navinfo"> <nav class="navitems"> <ul> <li class="ServiceAnass"><h3>ServiceAnass</h3></li> </ul> </nav> </div> <div class="title"> <h2>200dh Competition By Anass</h2> </div> <div class="form"> <div><h3>Fill in the information below</h3></div> <div><form action="/submit" method="post"> <div > <label class="firstname" for="firstname">Nom</label> <input type="text" name="nom" id="firstname"> </div> <div> <label class="lastname" for="lastname">Prenom</label> <input type="text" name="prenom" id="lastname"> </div> <div> <label class="ID" for="ID">ID</label> <input type="number" name="nombre" id="number"> </div> <div> <label class="nwhatsapp" for="nwhatsapp">Numero Whatsapp</label> <input type="number" name="nwhatsapp" id="nwhatsapp"></label> </div> <div class="screenshot-comb"> <label class="screenshot" for="screenshot">Screenshot</label> <input type="file" name="screenshot" id="screenshot"> </div> <div> <input type="submit" name="submit" value="Submit" id="submit"> </div> </form></div> </div> </div> </div> </body> </html> This is the client/settings.py: """ Django settings for client project. Generated by 'django-admin startproject' using Django 5.0.7. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path … -
Django project hosting with Vercel
I am trying to host my Django project on Vercel, but it shows some errors related to the 'requirements.txt' file in my project, something related to dependencies. This is the error message: Error: Command failed: pip3.12 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Cannot install -r /vercel/path0/requirements.txt (line 19) and idna==3.3 because these package versions have conflicting dependencies. ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts -
In Django, combining and ordering counts across two model fields
I have these two simplified models, representing people and letters that have been sent and received by those people: class Person(models.Model): name = models.CharField(max_length=200, blank=False) class Letter(models.Model): sender = models.ForeignKey(Person, blank=False) recipient = models.ForeignKey(Person, blank=False) I want to display a list of Persons ordered by how many times they've sent or received any letters. I started doing this very laboriously, but figure there must be a simpler way. e.g., this gets the Person IDs and counts of how many times they've sent a Letter: senders = ( Letter.objects.order_by() .values(person_id=F("sender")) .annotate(count=Count("pk")) .distinct() ) I can do the same for recipients. Then combine the two into a single list/dict, adding the counts together. Sort that. Then inflate that data with the actual Person objects, and pass that to the template. But I feel there must be a less laborious way, starting, I think, with a single query to get the combined sent + received counts. -
can't connect to mysql docker
when i launch the command 'python manage.py makemigrations' error : C:\Users\pc\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\commands\makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2003, "Can't connect to MySQL server on 'mysql' ([Errno 11001] getaddrinfo failed)") warnings.warn ( No changes detected im using docker and i launched mysql-container (dev-mysql) I am trying to launch django as backend with mysql database in docker container locally and stumble upon the error. i dont why know why im getting this problem, i tried so many solutions my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tp', 'USER': 'root', 'PASSWORD': '125', 'HOST': 'mysql', 'PORT': 3306, } } docker-compose version: '3.8' services: mysql: image: mysql:8.0 container_name: dev-mysql restart: always environment: MYSQL_ROOT_PASSWORD: 125 MYSQL_DATABASE: tp ports: - "3307:3306" volumes: - mysql_data:/var/lib/mysql # Use the named volume networks: - my_bridge healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] interval: 30s timeout: 10s retries: 5 backend-app: image: backend:latest # Use the already built image container_name: backend-app restart: always ports: - "8001:8000" depends_on: mysql: condition: service_healthy networks: - my_bridge healthcheck: test: ["CMD-SHELL", "curl -f http://localhost:8000/admin/login/?next=/admin/ || exit 1"] interval: 30s timeout: 10s retries: 5 frontend-app: image: frontend-app:latest # Use the already built image container_name: frontend-app restart: always ports: … -
why my django app not including content-type on request headers?
I have simple Django app with some request send via ajax and django will return different responses depends on content-type I declare on ajax request. This code work fine on my local computer, however in my hosting server I always get 500 server error , it return keyerror: content-type. After checking headers list I notice that content-type not exist in the headers list on hosting, but in my local computer it exists. Django lines: if request.headers['content-type'] == 'application/json': response = render_to_string(self.templates, {'form': form}, request) data = {'success': True, 'rendered': response, 'title': self.title} return JsonResponse(data) else: return render(request, 'base.html', {'form': form, 'title': self.title, 'template': self.templates}) AJAX Lines: $.ajax({ url: link, contentType: 'application/json', dataType: 'json', success: function(data){ $('title').html(data.title); $('#content').html(data.rendered); window.history.pushState({'data': data, 'path': link}, "", link) $('#nav-menu').attr('data-path', link); I confuse what the cause, I already collected staticfiles. -
Deployed Django app returning 301s and NS_ERROR_REDIRECT_LOOP
I've just setup my Django app in my VPS using gunicorn and nginx, and I cannot access it in my browser through the custom domain that I assigned it to (ipantun.com) because it keeps returning 301s and finally stopped with NS_ERROR_REDIRECT_LOOP. I followed this tutorial, and everything works fine with running it locally and also using gunicorn. So I suspect it may have something to do with how I configure my nginx and maybe even Cloudflare which is my domain registrar. A thing that I noticed is if I go to the URL ipantun.com, then it will redirect to www.ipantun.com and it will also query the full URL as its URI as in the final URL will be https://www.ipantun.com/www.ipantun.com. I expected the redirect of non-www to www as I have setup a Redirect Rule on Cloudflare to do so, but the querying is something I've never encountered before so I'm lost. Every log files of gunicorn and nginx showed nothing wrong. Everything in /etc/nginx/sites-available is also in /etc/nginx/sites-enabled. Not sure if it's relevant, but I'm also serving another React app from the same server on the same port ie. port 80. But as you'll see in the nginx config files … -
can't connect to mysql server - docker
I want to launch python manage.py makemigrations im using docker and i launched mysql-container I am trying to launch python backend with mysql database in docker container locally and stumble upon the error : i dont why im getting this problem, i tried so many solutions "Can't connect to MySQL server on 'mysql' ([Errno 11001] getaddrinfo failed)") warnings.warn( No changes detected my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tp', 'USER': 'root', 'PASSWORD': '125', 'HOST': 'mysql-container', # ou 'localhost' si vous utilisez un port local 'PORT': '3306', } } my docker-composer services: mysql: image: mysql:latest container_name: mysql-container hostname: 'mysql' restart: always environment: MYSQL_USER: root MYSQL_ROOT_PASSWORD: 125 MYSQL_DATABASE: tp ports: - "3306:3306" volumes: - mysql_data:/var/lib/mysql # Use the named volume networks: - my_bridge healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] interval: 30s timeout: 10s retries: 5 backend-app: build: context: ./backend # Assure-toi que le chemin est correct dockerfile: Dockerfile # Assure-toi que le Dockerfile est présent image: backend:latest # Use the already built image container_name: backend-app restart: always ports: - "8000:8000" depends_on: mysql: condition: service_healthy networks: - my_bridge healthcheck: test: ["CMD-SHELL", "curl -f http://localhost:8000/admin/login/?next=/admin/ || exit 1"] interval: 30s timeout: 10s retries: 5 frontend-app: build: context: ./frontend dockerfile: Dockerfile … -
Choreo: Connecting Repo without Creating a Component?
Choreo newbie here... I am going through Tech With Tim's YouTube tutorial named "Django & React Web App Tutorial - Authentication, Databases, Deployment & More..." and I ran into a difference between his video (made March 2024) and how Choreo works now (19 Oct 2024). In Tim's video, he made a new project, linked it with a GitHub repo but without creating an initial component (see screenshot below). Is there a way to still do that? Image from video from Tech With Tim I started by creating a project by entering a name and clicking "Create". New Project dialog Then clicked "Start" in the "Create Multiple Components" section to connect a Git repository. Connect Repo But there is no way to then create the project with the connected repo without creating a component. Must create a component Is the way Tim did it in his video not available anymore? Did I make a mistake somewhere that took me in a different path? -
Python Django Course Project
I need help with my Django Project to finish and submit it by tomorrow @2pm GMT. The Project detail is to build a RESTFUL API for a library management system. I have already built the database Models and done the necessary configurations for the Books, Library Attendant, the Authors, Checking out. Also built the views for all the basic operations that will take place... Looking for help with the user authentication for the Django Application, I will need help with some errors that pop-up in the browser when the server is started. Anyone who is good with Django and wants to help me should please reach out to me here on Stack overflow or e-mail at znyadzi1@gmail.com Your help is greatly appreciated. Thanks and Regards Zoe Nyadzi I tried to use AI support for the project but it seems not to be going on well. I tried all the odds devv ai, chatGPT, Copilot, but to no avil. -
Getting Id of another Django form inside of other Django form
Hi guys i want to create multi step form like this: ask for connection name and connection type and save it in database and after that redirect user to new form for connection details but i want one field as foreign key pointed to item created in last form. models: from django import models class Form1Model(models.Model): name = models.CharField(max_length=100) connection_type=models.CharField(max_length=100) def __str__(self) -> str: return self.name class Form2Model(models.Model): name=models.CharField(max_length=100) protocol=models.CharField(max_length=5) connection_name=models.ForeignKey(Form1, on_delete=models.CASCADE) def __str__(self) -> str: return self.name my forms: from django import forms from inventory.models import Form1, Form2 class Form1Form(forms.ModelForm): class Meta: model = Form1 fields = "__all__" class Form2Form(forms.ModelForm): form1 = forms.ModelChoiceField(queryset=Form1.objects.all()) class Meta: model = Form2 fields = ["form1", "name", "protocol"] now i want to know how i must create my views thnx for help guys. -
cant connect to mysql server
I want to launch python manage.py makemigrations im using docker and i launched mysql-container I am trying to launch python backend with mysql database in docker container locally and stumble upon the error : i dont why im getting this problem, i tried so many solutions "Can't connect to MySQL server on 'mysql' ([Errno 11001] getaddrinfo failed)") warnings.warn( No changes detected my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tp', 'USER': 'root', 'PASSWORD': '125', 'HOST': 'mysql', # ou 'localhost' si vous utilisez un port local 'PORT': '3306', } } my docker-composer services: mysql: image: mysql:latest container_name: mysql-container restart: always environment: MYSQL_USER: root MYSQL_ROOT_PASSWORD: 125 MYSQL_DATABASE: tp ports: - "3306:3306" volumes: - mysql_data:/var/lib/mysql # Use the named volume networks: - my_bridge healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] interval: 30s timeout: 10s retries: 5 i want to make migrations on django -
How to stop auto generating text in ShortUUIDField field
I have a model where ShortUUIDField automatically generating ids I want to disable the auto generation class Mymodel(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") sample_id = ShortUUIDField(length=10, max_length=100, prefix="var", alphabet="abcdef", null=True, blank=True,default=lambda: None) I added default=lambda: None in sample_id field but it is still automatically generating the ids. I want the id default to be blank -
gRPC - postgres connection issue in django: connection already closed
I am using django-grpc-framework in my django rest project. I setup a grpc service to get some user information from this project using grpc server. This grpc service is running using kubernetes, and after a while of running, I get the following error: django.db.utils.InterfaceError: connection already closed I restart the deployment and the issue goes away. I recently added the following line after every grpc service method: django.db.close_old_connections() but now I see that some rpc calls take 20 ms to connect to the database, and this is slowing the response time. Is there any other way to fix my problem without causing long response times. -
Django template not loading correctly
In my django project i am using a template named main.html in this html file i am importing all the required css and js files i will share the structure below {% load static %} <!-- site Favicon --> <link rel="icon" href="{% static 'img/favicon/favicon.png' %}" sizes="32x32"> <!-- css Icon Font --> <link rel="stylesheet" href="{% static 'css/vendor/gicons.css' %}"> <!-- Tailwindcss --> <script src="{% static 'js/plugins/tailwindcss3.4.1' %}"></script> {% block content %} {% endblock %} <script src="{% static 'js/plugins/jquery-3.7.1.min.js ' %}"></script> and i am extending this template to product-details.html file like below {% extends 'index/main.html' %} {% load static %} {% block content %} content of the product-details.html {% endblock %} now the problem is css of this product-details.html is not loading correctly and i am using tailwind as a framework is my way of extending template correct? I tried to load the page but css not loading properly -
dJango Production and Test database QC check on data
I am looking to create a data QC check between our production and development environments. This is to ensure our systems templates are set up the same, there will be NO data writing to the database read-only the models are as such: class Plan(models.Model): DatabaseOperations.max_name_length = lambda s: 40 # Define fields that match the columns in your existing table PROJECT_CODE = models.TextField(primary_key=True) PROJECT_NAME = models.TextField() IS_TEMPLATE_PROJECT = models.TextField() PLANTYPE = models.TextField() ABR_SUPP_BY_SSG = models.TextField() class Meta: db_table = '\"schema\".\"table\"' # specify the schema and table name managed = False # Prevent Django from managing the table schema def __str__(self): return self.PROJECT_NAME class Activity(models.Model): DatabaseOperations.max_name_length = lambda s: 40 # Define fields that match the columns in your existing table ACTIVITY_ID = models.TextField(primary_key=True) PROJECT_CODE = models.ForeignKey(Plan, on_delete=models.DO_NOTHING, db_column='PROJECT_CODE', related_name='activities') ACTIVITY_NAME = models.TextField() LINE_IDENTIFIER = models.IntegerField() class Meta: db_table = '\"schamea\".\"table\"' # specify the schema and table name managed = False # Prevent Django from managing the table schema def __str__(self): return self.ACTIVITY_NAME I am using an HTML form to allow the users to select the database to use (more will be added later <form method="GET" action="{% url 'list_plans' %}"> <label for="Databases">Choose Databases:</label><br> <input type="checkbox" id="db1" name="databases" value="db1"> <label for="db1">Production</label><br> <input … -
Force host part in BASE url when using Vite's development server
I have a somewhat non-conventional setup where I use a Vite/Vue SSR server for template rendering behind a Django server. I.e. Django calls node, gets html back, and sends it back to the browser. I encountered a problem with Vite's dev server in that it doesn't respect a full BASE url like https://bar.com/foo/ (it strips out the origin part, which is documented behavior). Without the origin part, however, the generated html and other assets contain urls that the browser treats as relative to the origin of the Django server, which obviously doesn't work. Is there a way to force Vite to include the origin in the BASE url, or is my only option to proxy back to the Vite server from Django? -
getting error in google sign in using javascript
when im trying to sign in through google I'm able to proceed but at this point its showing blank strong text {% block content %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="referrer" content="strict-origin-when-cross-origin"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="google-signin-client_id" content="my client id"> <title>Google Sign-In with JWT</title> <script src="https://accounts.google.com/gsi/client" async defer></script> </head> <body> <h1>Google Sign-In</h1> <div id="g_id_onload" data-client_id = "my client id" data-callback ="handleCredentialResponse" data-login-uri = "http://127.0.0.1:8000/user/login/" data-auto_prompt ="false"> </div> <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"> </div> <script> console.log("Current origin:", window.location.origin); function handleCredentialResponse(response) { console.log("Received response from Google Sign-In"); const idToken = response.credential; console.log("ID Token:", idToken); fetch('http://127.0.0.1:8000/user/login/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify({ token: idToken }), credentials: 'include' }) .then(response => { console.log("Received response from server"); return response.json(); }) .then(data => { if (data.access) { console.log("JWT Token:", data.access); localStorage.setItem('jwt', data.access); alert('Login successful!'); } else { console.error("Login failed:", data); alert('Login failed!'); } }) .catch(error => { console.error('Error:', error); alert('An error occurred during login'); }); } window.onload = function() { console.log("Page loaded. Google Sign-In should initialize soon."); }; </script> </body> </html> tried everything but not move ahead using javascript more specifically HTML page to just get idToken from google and then sending it to backend …