Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To download a functioning pdf in django using wkhtmltopdf?
I have a django project, where i download the template as a pdf using wkhtmltopdf.The pdf is downloaded when i click the download button, However when i open the pdf it says, "Error Failed to load PDF document." and i cant open the downloaded pdf. Upon looking at the terminal i see this error: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. What is causing this issue and how can it be solved? this is my views.py: @login_required def download_resume(request): # Retrieve data from your Django models personal_info = personalinfo.objects.filter(user=request.user).last() summaries = summary.objects.filter(user=request.user).last() experiences = experience.objects.filter(user=request.user) educations = education.objects.filter(user=request.user) certs = certificates.objects.filter(user=request.user) skillset = skills.objects.filter(user=request.user) # Generate the PDF content using a template template = get_template('template0.html') context = { 'personal_info': personal_info, 'summaries': summaries, 'experiences': experiences, 'educations': educations, 'certs': certs, 'skillset': skillset } # Render the template with the context data html_content = template.render(context) # Configure pdfkit with the path to wkhtmltopdf pdfkit_config = pdfkit.configuration(wkhtmltopdf='C:/Users/lulu/PProjects/resumebuilderproject/wkhtmltopdf/bin/wkhtmltopdf.exe') # Convert HTML to PDF using wkhtmltopdf pdf = pdfkit.from_string(html_content, False, configuration=pdfkit_config) # Create a response with the PDF content response = FileResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="resume.pdf"' … -
Django StreamingHttpResponse for text not streaming
I am having trouble with streaming a simple text response with django. it's a very straight-forward demo. python3.11.4 django4.2.5 python serve a text generator with delay @csrf_exempt def testPost(request): if request.method == 'POST': print('--- post') def gen1(): for i in range(10): time.sleep(0.5) print(f'----- {i}') yield str(i) return StreamingHttpResponse(gen1(), content_type="text/plain", buffered=False) js tries to get response bit by bit function testPost(messages, success, error) { const xhr = new XMLHttpRequest(); xhr.open("POST", apiUrl); xhr.responseType = "text"; xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onprogress = (event) => { const partialResponse = xhr.responseText.substring( xhr.loadedBytes || 0, event.loaded ); xhr.loadedBytes = event.loaded; success(partialResponse); // Handle the partial response }; xhr.onload = () => { console.log('---loaded'); success(xhr.responseText); // Handle the final response }; xhr.onerror = error; const requestData = new URLSearchParams({ messages: JSON.stringify(messages), }).toString(); xhr.send(requestData); } // Usage chatPost(messages, (partialResponse) => { console.log(partialResponse); // Handle the partial response }, (error) => { console.error(error); }); here's the output: server goes first 2023-10-01 07:21:02,946 INFO Listening on TCP address 127.0.0.1:8001 --- post ----- 0 ----- 1 ----- 2 ----- 3 ----- 4 ----- 5 ----- 6 ----- 7 ----- 8 ----- 9 127.0.0.1:35074 - - [01/Oct/2023:07:21:11] "POST /api/test/" 200 10 frontend result comes after all logging in server 0123456789 --loaded 0123456789 note that … -
Cart Popover is not working on all pages of my site the past added products only shows on that page where they are present. Django Problem
The Cart only works when the cart is empty or woks on the page where the added products are present. And if not then it stops working and cart +,- function also stops working and cart shows Cart(0). I have taken the navbar code from bootstrap. Base.html: //Navbar <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/products">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> <li class="nav-item"> <a class="nav-link" href="/contacts">Contact Us</a> </li> </ul> <form class="form-inline" method="post" action="/search/">{% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id=search> <button class="btn btn-outline-info my-2 my-sm-0" type="submit">Search</button> </form> <button type="button" class="btn btn-secondary" style="margin-left: 10px; background-color: darkcyan; border: 0;" data-container="body" data-toggle="popover" data-placement="bottom" id="popcart" data-html="true" data-content="Bottom popover"> Cart(<span id="cart">0</span>) </button> </div> </nav> //Normal Html has been removed form this code. Only JS script here. {% block js %} <script> if (localStorage.getItem('cart') == null) { var cart = {}; } else { cart = JSON.parse(localStorage.getItem('cart')); updateCart(cart); } //$('.cart').click(function(){ $('.divpr').on('click', 'button.cart', function() { var idstr = this.id.toString(); if (cart[idstr] != undefined) { qty = cart[idstr][0] + 1; } else { qty … -
Failed to access chromadb from django app with docker compose, HTTPConnectionPool(host='127.0.0.1', port=8989): Max retries exceeded with url
I am trying to build a REST api with django and chromadb, I built two containers: django for RESTApi, chroma for vector database. Two containers are running successfully. Here is my docker-compose file: version: '3.9' services: django: container_name: django build: context: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/Users/apple/Docker/app/ ports: - '8000:8000' expose: - 8000 chroma: container_name: chroma image: ghcr.io/chroma-core/chroma:latest volumes: - index_data:/Users/apple/Docker/app/data ports: - '8989:8989' expose: - 8989 volumes: index_data: name: my-db-data Here is my Dockerfile: FROM python:3.9 WORKDIR /Users/apple/Docker/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt /Users/apple/Docker/app/requirements.txt RUN pip3 install -r requirements.txt COPY ./entrypoint.sh /Users/apple/Docker/app/entrypoint.sh COPY . /Users/apple/Docker/app/ EXPOSE 8000 ENTRYPOINT ["/Users/apple/Docker/app/entrypoint.sh"] I am trying to establish a connect from django to chromadb, as following: from rest_framework.decorators import api_view from rest_framework.response import Response import chromadb from chromadb.config import Settings chroma_client = chromadb.HttpClient( host='localhost', port=8989, settings=Settings(allow_reset=True, anonymized_telemetry=False)) @api_view(['GET']) def index(request): sample_collection = chroma_client.get_or_create_collection(name="sample_collection") print(sample_collection) return Response({ 'info': 'Hello world.' }) I got this error message: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=8989): Max retries exceeded with url: /api/v1/collections (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f35e0e3c4f0>: Failed to establish a new connection: [Errno 111] Connection refused')) I did some research, it seems like the problem of port conflict, … -
JWT Authentication Error (401) When Fetching Django API Data from React App via Cookies
I have an API created in Django, which uses a JWT token to validate the user's authentication. Once I log in, I obtain a token that I use to call the 'hello' endpoint to fetch information. Everything works perfectly in this regard, but the problem arises when I integrate it into my React app. My React app allows me to log in and store the JWT token in cookies. In the 'Home.js' file, there's a button responsible for fetching data from the 'hello' endpoint. When I make the request, the Django API responds with a 401, unauthorized error. If I add token into headers, it works but I don't know if this is the way or I should do in another way: const jwtToken = 'mytoken'; const response = await axios.get("http://localhost:8000/api/hello/", { withCredentials: true, headers: { 'Authorization': `Bearer ${jwtToken}`, } views.py: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated class HelloView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): content = {'message': 'Hello, World!'} return Response(content) settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see … -
Regarding the accessing the form field of a django wizard form
`Dear All, I am new to Django and eager to learn it. I have created a Django wizard form with three steps. I defined only one model and separated it into three form classes. Now I want to access these form classes manually to render it into the HTML. But I am not able to do it. Like in the case of forms we can access the files by using the below given syntax. {{all_forms.Participation_Year.label_tag}} {{all_forms.Participation_Year}} I want a similar type of syntax for this. models.py class Test_session(models.Model): Subject_ID = models.CharField(max_length=20) Participation_Year = models.CharField(max_length=20) Phone_Number = models.CharField(max_length=20) Gender = models.CharField(max_length=20) Blood_Group =models.CharField(max_length=20) Age = models.CharField(max_length=20) DOB = models.CharField(max_length=50) POB = models.CharField(max_length=100) City = models.CharField(max_length=100) District = models.CharField(max_length=100) views.py class MyWizard(SessionWizardView): form_list = [Step1Form, Step2Form, Step3Form] # List of forms for each step template_name = 'participants/test_session.html' # Create a template for your multi-page form #print(len(form_list)) def done(self, form_list, **kwargs): # Collect data from each form step data = {} for i, form in enumerate(form_list): data.update(form.cleaned_data) print(f"Step {i+1} data:", form.cleaned_data) # Create a new instance of your model and save the data form_data = Test_session(\*\*data) # form_data.save() # Redirect to a thank you page or another URL return HttpResponseRedirect('/thank-you') urls.py path('my-form/', MyWizard.as_view(), … -
csrf_exempt true on all callbacks
I've created some custom middleware for my django rest api to enforce a CSRF security policy of setting custom headers. I've subclassed CsrfViewMiddleware and overriden a few methods to suite my needs, most notably the check_token method. However, I noticed later on that all requests have been coming in with the attribute "csrf_exempt" set to true, even though nowhere have I used the csrf_exempt decorator. I've searched through the django docs to try and figure out why this has been happening to no avail. Here is my custom middleware: class CustomCsrfMiddleware(CsrfViewMiddleware): def _reject(self, request, reason): logger.warning("Forbidden (%s): %s", reason, request.path) return Response( {'detail': 'Forbidden', 'reason': reason}, status.HTTP_403_FORBIDDEN ) def _check_token(self, request): # Get the two relevant pieces of information, the # the returned csrftoken in the custom header and the hmac try: hmac = _get_hmac(request) except BadDigest as e: raise RejectRequest(e.reason) try: request_csrf_token = request.META[settings.CSRF_HEADER_NAME] token_source = settings.CSRF_HEADER_NAME except KeyError: raise RejectRequest(REASON_CSRF_TOKEN_MISSING) try: _check_token_format(request_csrf_token) except InvalidTokenFormat as e: reason = self._bad_token_message(e.reason, token_source) raise RejectRequest(reason) if not _does_match(request_csrf_token, hmac): reason = self._bad_token_message("incorrect", token_source) raise RejectRequest(reason) def process_request(self, request): try: csrf_secret = self._get_secret(request) if csrf_secret is None: raise InvalidTokenFormat(REASON_CSRF_TOKEN_MISSING) except InvalidTokenFormat: _add_new_csrf_cookie(request) else: if csrf_secret is not None: request.META["CSRF_COOKIE"] = csrf_secret def … -
Forbidden (Origin checking failed - https://api.example.com does not match any trusted origins.): /admin/login/
I'm running a Django app over DigitalOcean's Kubernetes, the site runs over https but when I try to use the Django Admin from the domain, it throws a 403 forbidden error but if I connect directly to the Pod it succeeds. I wondered if it has to do with the ingress set up that is not recognizing the paths of api.example.com. Here's the ingress.yaml file apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: backend-ingress annotations: kubernetes.io/ingress.class: "nginx" cert-manager.io/cluster-issuer: "letsencrypt-prod" spec: ingressClassName: nginx tls: - hosts: - example.com - api.example.com secretName: tls-secret-name rules: - host: api.example.com http: paths: - pathType: Prefix path: "/" backend: service: name: backend port: number: 8000 - host: example.com http: paths: - pathType: Prefix path: "/" backend: service: name: frontend port: number: 3000 Any clue? -
How to Update Django 1.6 Project to the Latest Version
I have an existing Django project that was originally developed using Django version 1.6. Now, I'd like to upgrade it to the latest version of Django to take advantage of new features, security updates, and improvements Updating Django Version Running pip install Reviewing the Official Documentation -
django channels closing external connection to websocket
Any one can help with it? So i open connection to external wesocket and i want if my boolean field in db is False, Close this connection. When im update my db i'm using signals.py for pass data from it to consumers.py, in consumer i get method that do like this async def receive(self, text_data): try: # Handle incoming WebSocket messages here data = json.loads(text_data["text_data"]) # Get the inner dictionary # Access specific fields from the data dictionary trade_id = data.get("id") symbol = data.get("symbol") interval = data.get("interval") length = data.get("length") barlimit = data.get("barlimit") user_id = data.get("user") monitoring_status = data.get("monitoring_status") if monitoring_status is True: logger.info( f"start binance websocket: {monitoring_status}, {trade_id}, {symbol}, {interval}, {length}, {barlimit}" ) await self.start_binance_websocket(user_id, trade_id, symbol, interval, length, barlimit) else: logger.info( f"stop binance websocket: {monitoring_status}, {trade_id}, {symbol}, {interval}, {length}, {barlimit}" ) await self.stop_binance_websocket(user_id, trade_id, symbol, interval, length, barlimit) # Now you can use these variables as needed in your consumer logic # For example, you can log them or perform other actions except Exception as e: logger.error(f"Error receiving message: {e}") in start_binance_websocket i save data for connection in self.active_connections and if i change value of monitoring_status to False im calling function async def stop_binance_websocket(self, user_id, trade_id, symbol, interval, … -
"django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured" Error in my site
The error: (venv) gamedeveloper@animechatapp:~$ sudo journalctl -u gunicorn -n 50 [sudo] password for gamedeveloper: Sep 30 13:10:33 animechatapp gunicorn[510664]: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not co> Sep 30 13:10:33 animechatapp gunicorn[510664]: [2023-09-30 13:10:33 +0000] [510664] [INFO] Worker exiting (pid: 510664) Sep 30 13:10:33 animechatapp systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 30 13:10:33 animechatapp systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 30 13:19:35 animechatapp systemd[1]: Started gunicorn.service - gunicorn daemon. Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Starting gunicorn 21.2.0 Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Listening at: unix:/run/gunicorn.sock (510824) Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Using worker: sync Sep 30 13:19:35 animechatapp gunicorn[510825]: [2023-09-30 13:19:35 +0000] [510825] [INFO] Booting worker with pid: 510825 Sep 30 13:19:35 animechatapp gunicorn[510826]: [2023-09-30 13:19:35 +0000] [510826] [INFO] Booting worker with pid: 510826 Sep 30 13:19:35 animechatapp gunicorn[510827]: [2023-09-30 13:19:35 +0000] [510827] [INFO] Booting worker with pid: 510827 Sep 30 13:19:40 animechatapp gunicorn[510827]: - - [30/Sep/2023:13:19:40 +0000] "POST /update_active_status/ HTTP/1.0" 200 21 "http://194.195.119.23> Sep 30 13:19:43 animechatapp gunicorn[510826]: - - [30/Sep/2023:13:19:43 +0000] "POST /update_active_status/ HTTP/1.0" 200 21 "http://194.195.119.23> Sep 30 13:20:01 animechatapp gunicorn[510826]: - - [30/Sep/2023:13:20:01 +0000] "POST /update_active_status/ HTTP/1.0" … -
How save the result from task in database using django_celery_results?
I am beginner with Celery, and i need to save the result of the task in the database here is tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task import hashlib from project.celery import app from .models import Puzzle @shared_task(ignore_result=False) def solve_puzzle(data, level): # try to find a nounce value that makes the SHA-1 hash of the data and the nounce start with a certain number of zeros solution = "" nounce = 0 while not solution.startswith("".join(["0" for _ in range(level)])): solution = hashlib.sha1(f"{data}{(nounce)}".encode()).hexdigest() nounce += 1 return nounce, solution the celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost', backend='db+sqlite:///results.sqlite') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.retry = 360 app.conf.timeout = 300 # Load task modules from all registered Django apps. app.autodiscover_tasks() settings.py: CELERY_RESULT_BACKEND = 'django-db' I run celery using the command: celery -A project worker -l INFO then got : `[2023-09-30 19:29:13,461: INFO/MainProcess] Task puzzle.tasks.solve_puzzle[e1960235-801d-4bc4-8f5d-e7fb923830ba] received [2023-09-30 19:29:15,909: INFO/SpawnPoolWorker-21] child process 624 calling … -
Can we implement Airflow in a Django project for scheduling tasks?
I'm working on a Django rest project to create different API endpoints. I want to implement airflow that reads a text file and stores it in a Django Model daily. I have installed Apache airflow, created a DAG, and changed my dag location in the airflow.cfg file. But when I run the webserver and the scheduler I cannot see my dag in the DAG's list. Can somebody help me with the airflow django implementation? -
is this erroro comming due to problem in server or code error
where i made mistake in django code code error for loop and if else in django html code <!doctype html> <style> table, th, td{ border:1px solid black; padding-right: 2px; } </style> <title>divyanshu jha</title> </head> <body> <h1>this is heading 1</h1> <h2>{{title}}</h2> {%for n in a%} <div>{{forloop.counter}}{{n}}</div> {% endfor %} <table> <tr> <th>phone no</th> <th>name</th> <th>age</th> </tr> {% for i in user_detail%} <tr> <td style="width:400px">{{i.phone}}</td> <td>{{i.name}}</td> <td>{{i.age}}</td> </tr> {% endfor %} </table> {% if dj|length > 0 % } {% for ch in dj %} {% if ch > 12 %} <div>{{ch}}</div> {% endif %} {% endfor %} { % else %} no data found {% endif %} </body> django code from django.http import HttpResponse from django.shortcuts import render def aboutus(request): return HttpResponse("hello") def difficult(request,userid): return HttpResponse(userid) def homepage(request): x={ "title":"divyanshu jha", "a":['mumbai','dj','hello','meow'], "dj":[10,11,12,15,16,17,18,19], "user_detail":[ {'name':'divyanshu jha','phone':7977879695, 'age':16}, {'name':'dipti jha','phone':7977879695, 'age':40}, {'name':'ajun jha','phone':9322864840, 'age': 47,},] } return render(request,"index.html",x) -
Django and chroma with docker-compose error: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url
I am trying to build a REST api with django and chromadb, I built two containers: django for RESTApi, chroma for vector database. Two containers are running successfully, as shown: enter image description here Here is my docker-compose file: enter image description here Here is my Dockerfile: enter image description here I'm trying to establish the connection with chromadb from django, here is my code: enter image description here It gives me the error: enter image description here I did some research, it shows that this is the problem of port or host, but I do not have a clue how to fix it. I hope to get the help from the kind people in this community to fix it. -
use up.render to rerender a section in django using unpoly and alpinejs
I am building an ecommerce website using Django with Alpine and Unpoly, In home page i got a list of products so its making a lot of queries which means it takes time, long story short, I got a functionality for adding product to wishlist and removing it from wishlist, for the a tag that added/removed a product to/from wishlist I added up-follow to not refreshing the page. It works, but the problem is that it rerender the whole page(without refresh) which means its making the same queries again when instead I want to only rerender the AddToWishlist/RemoveFromWishlist part so the site wont be slow, this is how it looks: This is the code that renders the a tags: {% is_product_in_wishlist request product as is_in_wishlist %} {% if is_in_wishlist %} <a href="{% url 'products:remove-from-wishlist' product_id=product.id %}" id="id__{{product.id}}" class="absolute top-0 right-0 inline-block text-black transform duartion-200 rounded-full bg-white m-1 p-1 two" up-follow @click='removeFromWishlist'> <svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" fill="currentColor" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" aria-hidden="true" class=""><path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path></svg> </a> {% else %} <a href="{% url 'products:add-to-wishlist' product_id=product.id %}" id="id__{{product.id}}" class="absolute top-0 right-0 inline-block text-black transform duartion-200 rounded-full … -
Django how to filter products by multiple fields
I have a db containa products(name, origin place, price, img...) and I want to filter them by place or price or both when i chose from form. My models: class ProductFilter(models.Model): place = models.CharField(max_length=50) price = models.CharField(max_length=50) def __str__(self): return self.name My forms: class ProductFilterForm(forms.Form): place = forms.ChoiceField(choices=place_choices, widget=forms.Select()) price = forms.ChoiceField(choices=price_choices, widget=forms.Select()) class Meta: model = ProductFilter fields = ('place', 'price') with place_choices: place_choices = ( ("A","All"), ("C","Cellphones"), ("M","Media Mart"), ("N","Nguyễn Kim") ) price_choices: price_choices = ( ("", "All"), ("A", "Giá thấp > cao"), ("B", "Giá cao > thấp") ) My views right now: def show_db(request): place = ProductPlaceForm() newForm = ProductNameForm() filterForm = ProductFilterForm() product_list = Product.objects.all() ft_place = request.POST.get('place', None) ft_price = request.POST.get('price', None) print(ft_place) print(ft_price) return render(request, 'product_list.html', {'product_list' : product_list, 'form':newForm, 'place':place, 'filterForm':filterForm}) My template: {% block content %} {{filterForm}} <ul class="d-flex flex-row flex-wrap align-content-center justify-content-around align-items-center list-unstyled"> {% for p in product_list %} <li> <div class="card h-100 mt-2 border-dark mb-3" style="max-width: 18rem;"> <img src="{{p.img}}" class="card-img-top" style="height:17.813em;width:auto;" alt="product image"> <div class="card-body"> <h5 class="card-title">{{p.name}}</h5> <p class="card-text">{{p.current_price}}</p> <p class="card-text">Store: {{p.place}}</p> <p class="card-text">Add at {{p.date_add}}</p> <a href="{{p.url}}" target="_blank" class="btn btn-primary">Go to store</a> </div> </div> </li> {% endfor %} </ul> {% endblock %} I believe i have to redirect … -
Django : django.db.utils.OperationalError: no such table: Blog_username
django.db.utils.OperationalError: no such table: Blog_username i got this error,I have designed my model already and I wanted to add a new table to the model called username in my models.py using SQLite in my Django application called Blog. And after adding it to my model I then use the following command to add it to my database: python manage.py makemigrations python manage.py migrate And I didn't get any error while running this command. But later when i wanted to query the data in my database using the following command: python manage.py shell from Blog.models import Person Note: Person is the name of the class in my database Person.objects.all() After running the last command I then got an error saying django.db.utils.OperationalError: no such table: Blog_username and I have already makemigrations and also migrate and I got the error. Please I would really appreciate it if anyone could help me with this error and it really bothering me -
Saving Django form displayed on template like {{form.item}}
Django beginner here. I'm trying to understand something : In my template if I'm rendering my form like this {{form}} and click my button <button name="button" type="submit" onclick="">Save Form</button> The form is correctly saving. But if I change the way I'm displaying my form like : {{form.item1}} {{form.item2}} {{form.item3}} to be more flexible on my template, it doesn't save anymore. Is there a way to achieve this ? -
Changing color of a ul class wrapped within a specific hiearchy
<div class="one"> <nav id="sidebar" class="col-md-auto col-lg-2 d-md-inlineblock fontsize-5rem text-white sidebar"> <div class="position-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a href="{% url 'dashboard:dashboard' %}" class="nav-link active">Dashboard</a> </li> I am trying to figure out how to customize the background of wrapped within a specific hierarchy. I want to specifically change the color of nav-link active class here. How do I go about it? Is there any issue with any declaration here and the way it is framed? I confess that I do not know much about html except what I have gathered from Dash module in python. If possible, please also suggest me a way to go around managing the page structure of Django Dash wherein how do I configure the page setup if I am uploading Django dash set up directly in html template? Thank you! Color does not change. If other items on vertical tabs get selected, they change color but not the main first tab. -
Building Django app with Database server failure
I have Django app that is running on docker on serve and a database that running on another machine .My app has some API that doesn't need data base just call another service, So I want to be able to build my app even on database failure and it failure don't make my app exit. and users be able to use independent database API's. I try to catch connection failure by using try catch block in Django setting but it didn't work, Is it possible to do what I need? -
Django select_related() and prefetch_related() don't solve N+1 problem with nested objects
I'm trying to solve N+1 problem right now. I'm aware of select_related() and prefetch_related() methods but unfortunately the query I'm requesting to DB still not efficient enough. I have Comment model which has ForeignKey/M2M relations. class Comment(models.Model): profile = models.ForeignKey(Profile, related_name="comments", on_delete=CASCADE) post = models.ForeignKey(Post, related_name="comments", on_delete=CASCADE) parent = models.ForeignKey("self", related_name="children", blank=True, null=True, on_delete=models.CASCADE) reply_to = models.ForeignKey("self", related_name="replies", blank=True, null=True, on_delete=models.CASCADE) text = models.TextField(max_length=350) liked_by = models.ManyToManyField(Profile, related_name="comment_likes", blank=True) Comments system has just two-level layout (root comment and replies). But whenever I perform a query : comments = ( Comment.objects.filter(parent=None) .select_related("profile__specialization", "post", "parent", "reply_to") .prefetch_related("liked_by") .annotate(likes_count=Count("liked_by", distinct=True)) .order_by("-date_published") ) I'm still getting over 50 queries against DB to fetch profiles, posts etc. Even I remove select_related() and prefetch_related() at all I still get just 4-5 queries more. Serializers I use are just normal model.Serializer (requirements of a project pattern): class CommentDTOSerializer(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) profile = ProfileBaseDTOSerializer(read_only=True) post = PostBaseDTOSerializer(read_only=True) parent = BaseCommentDTOSerializer(read_only=True) reply_to = BaseCommentDTOSerializer(read_only=True) children = BaseCommentDTOSerializer(many=True, read_only=True) text = serializers.CharField(read_only=True) liked_by = ProfileBaseDTOSerializer(many=True, read_only=True) likes_count = serializers.IntegerField(read_only=True) I can't get what is wrong with my prefetching and why all the nested models (profile, post, parent, reply_to) are not prefetched correctly and still require DB to perform … -
Why can i remove user from many to many relation in django
I am unable to remove current user from a many to many relation in django class User(AbstractUser): pass class Post(models.Model): content=models.CharField(max_length=1000) owner=models.ForeignKey(User,on_delete=models.CASCADE) liked_by=models.ManyToManyField(User,symmetrical=False,related_name="liked_by",blank=True) Given above are my models def like(request,id): x=Post.objects.get(id=id) x.liked_by.add(request.user) x.save() return JsonResponse({"status":"successfully liked"}) def unlike(request,id): if request.method=="GET": x=Post.objects.get(id=id) x.liked_by.remove(request.user) x.save() return JsonResponse({"status":"successfully unliked"}) the above functions are used to like and unlike a post . I am able like ie add a user to the many to many relation but unable to remove {% extends "network/layout.html" %} {% block body %} {%for post in posts%} <div>{{post.content}} <button class="like" value="{{post.id}}">{%if request.user in post.liked_by.all%}unlike{%else%}like{%endif%}</button> </div> {%endfor%} <script> let like=document.querySelectorAll('.like') like.forEach(Element=>{ Element.addEventListener('click',(event)=>{ const clickedbutton=event.target if(clickedbutton.innerHTML==='like'){ fetch('like/'+clickedbutton.value) clickedbutton.innerHTML='unlike' } else if(clickedbutton.innerHTML==='unlike'){ fetch('unlike/'+clickedbutton.value) clickedbutton.innerHTML='like' } }) }) </script> {% endblock %} this is html i tried . my objective is to remove current user for many to many relation on clicking unlike -
Django Signals File
How does django know where exactly to look for Signal functions? like which .py file to search for receiver functions? Does it search for every single file and execute the function if found? Tried reading docs but didnt help much, Please help me out here. Django signals -
Unable to test websockets by using django channels
I'm trying to test my websockets but i'm getting '404 not found error' I have no idea why im getting error..i checked my code many times but still no use. Please have a look. This is my settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] ASGI_APPLICATION = 'routing_pro.asgi.application' and this is my consumers.py from channels.consumer import SyncConsumer,AsyncConsumer class MySyncConsumer(SyncConsumer): def websocket_connect(self,event): print('Websocket connected...',event) def websocket_receive(self,event): print('Websocket Recived...',event) def websocket_disconnect(self,event): print('Websocket disconnected...',event) class MyASyncConsumer(AsyncConsumer): def websocket_connect(self,event): print('Websocket connected',event) def websocket_receive(self,event): print('Websocket Recived',event) def websocket_disconnect(self,event): print('Websocket disconnected',event) and this is my asgi.py file: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter import myapp.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'routing_pro.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( myapp.routing.websocket_urlpatterns. myapp.routing.websocket_urlpatterns ) }) and this is my routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/sc/',consumers.MySyncConsumer.as_asgi()), path('ws/ac/',consumers.MyASyncConsumer.as_asgi()), ] This is the error im getting : Could not connect to ws://127.0.0.1:8000/ws/sc/ 15:12:33 Error: Unexpected server response: 404 Handshake Details Request URL: http://127.0.0.1:8000/ws/sc/ Request Method: GET Status Code: 404 Not Found Request Headers Sec-WebSocket-Version: 13 Sec-WebSocket-Key: xO8WLEzNls1BeFdnyPJlbw== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: 127.0.0.1:8000 Response Headers Date: Sat, 30 Sep 2023 09:42:33 GMT Server: WSGIServer/0.2 CPython/3.10.11 Content-Type: …