Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i connect django with mongoDb
Does it good to connect django version 4.2.7 With monogdb? Is is a good practice? What is the trade off If there . If not what is best DB AND DBMS to work with it Or just use django models I have seen that a djongo is not a good one because it has a lof of drowbacks -
Django add random character in filename
I want to upload image and overwrite if the file exist without changing the filename. It's already can overwrite the file but django always add random char on the end filename. How can i overwrite with the same filename ? Here are my code. foto_content_url = models.ImageField(null=True, blank=True, upload_to=foto_path) def foto_path(instance, filename): return '/', filename + '.jpg']) -
PostgreSQL database migration problem from my Django project to AWS Elastic Beanstalk
I've just finalised my project based on **Django ** and **PostgreSQL ** *locally * on my Windows 10 machine. When migrating to AWS Elastic Beanstalk using pgAdmin 4, I'm having problems with the database. Despite my efforts to deploy the project with its data, the database on AWS does not contain any of the information previously stored locally. I followed the recommended steps to export my PostgreSQL database with pgAdmin 4 and successfully deployed my Django project on AWS Elastic Beanstalk. However, I can't find the data in the AWS database. I tried to export my PostgreSQL database from pgAdmin 4 as a backup file. Then I imported this file into my AWS database. I expected all my data, such as tables, records, etc., to be copied from my local database to the database on AWS. I checked the permissions and configurations to make sure the login details were correct, but the data doesn't seem to have transferred correctly to the database on AWS. What steps have I missed or what specific configurations are required to ensure the complete transfer of data from my local database to AWS Elastic Beanstalk? -
how to save user progress?
I'm building a learning spoken languages website where the users get to guess pictures, and I'm using Django and React. How to make each user have its own data or, in other words, how to make each user have its own progress? What do I need in Django to do this? I have a solution which is to add a user column in the model I want to save the progress of, and when someone register, an instance of that model will be created. But in this way if I have so many users, I will have a huge database, does anyone know if there is a better way to do that? -
ModuleNotFoundError: No module named 'pygments'
I try to practive with Django REST Framework. I have installed pygments module via: (venv) pip install pygments I see it in installed modules: (venv) pip list Package Version ------------------- ------------ asgiref 3.7.2 Django 4.2.7 djangorestframework 3.14.0 numpy 1.26.1 pandas 2.1.2 pip 23.3.1 Pygments 2.16.1 But when I import it to use and run make migration: (venv) python manage.py makemigrations snippets .... from pygments.lexers import get_all_lexers ModuleNotFoundError: No module named 'pygments' How to solve this problem? I follow the toturial of Django REST framework: https://www.django-rest-framework.org/tutorial/1-serialization/ and stuck at this step. -
Django html table iterating pandas df and create scrollbar
I am working on a django project where I render a pandas df in the context. I then iterate through this data frame to display it in a table td td (html below). I would like to get this as a fixed size with horizontal and vertical scrollbars instead when the data frame is too large. How can I do this? Thnx! :-) <table style="margin-left: auto; margin-right: auto;"> <tr> {% for col in df.columns %} <td> <b>{{col}}</b> </td> {% endfor %} </tr> {% for index, row in df.iterrows %} <tr> {% for cell in row %} <td> {{cell}} </td> {% endfor %} </tr> {% endfor %} </table> -
itrate ManyToMany Field and save the instance of the field
Hi im developing django app for sending bulk email to Users, i have two models name Reminder and Mail , Reminder model has a Assign_to field which is ManyToMany Field with User model, i write a signal for Reminder model for When an instance Created, for every User that assigned in reminder an instance created in Mail model, i user for loop in signal, but i dont have error but it just dosnt work My Mail Model: ``class Mail(models.Model): sender = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, related_name="user_sender" ) recipient = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, related_name="user_recipient" ) subject = models.CharField( max_length=255, ) body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) is_archived = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) is_starred = models.BooleanField(default=False) cc = models.EmailField(blank=True, null=True) bcc = models.EmailField(blank=True, null=True) attachments = models.FileField(upload_to="attachments", blank=True, null=True) importance = models.CharField( max_length=20, choices=[("HIGH", "HIGH"), ("MEDIUM", "MEDIUM"), ("LOW", "LOW")] ) folder = models.CharField( max_length=20, choices=[("INBOX", "INBOX"), ("SENT", "SENT"), ("DRAFT", "DRAFT")], ) is_draft = models.BooleanField(default=False) reply_to = models.EmailField(blank=True, null=True) thread_it = models.CharField(max_length=255, blank=True, null=True) is_replied = models.BooleanField(default=False) tags = models.ManyToManyField("Tag", blank=True) is_forwarded = models.BooleanField(default=False) def __str__(self): return self.subject` ` MyReminder Model: class Reminder(models.Model): reminder = models.CharField( default=generate_pk, max_length=255, unique=True, editable=False, verbose_name="Reminder ID", ) title = models.CharField(max_length=255) description = models.TextField() date = … -
Hello, when ever i submit a contact page they show me the error
Here is the code Views.py enter image description here enter image description here models.py enter image description here Here is the image of my code. Please tell me the solution. How i submit my contact form in my django database. -
Django Channels group send doesn't send any data to the group
My websocket works, but doesn't send any data to the group # settings.py # WSGI_APPLICATION = 'gozle_ads.wsgi.application' ASGI_APPLICATION = 'gozle_ads.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } # consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class BannerConsumer(WebsocketConsumer): def connect(self): self.accept() self.room_name = "banner_changer" self.room_group_name = "banner_changer_group" async_to_sync(self.channel_layer.group_add)( self.room_name, self.room_group_name ) self.send(json.dumps({"messgae": "Connected to the banner websocket"})) def receive(self, text_data=None): async_to_sync(self.channel_layer.group_send)( "banner_changer_group", { "type": "banner_ads_socket", "value": f"{text_data}" } ) def disconnect(self, code): print("DISCONNECTED") def banner_ads_socket(self, event): print("BANNER ADS") print(event) # asgi.py import os from django.core.asgi import get_asgi_application from django.urls import re_path from channels.routing import ProtocolTypeRouter, URLRouter from ads.consumers import BannerConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gozle_ads.settings') ws_patterns = [ re_path(r"ws/banner/", BannerConsumer.as_asgi()) ] application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(ws_patterns), }) when I'm sending data to the receive method nothing is happening, method banner_ads_socket doesn't work. It doesn't raise any errors. First, I'm adding consumer to my group, then sending data to the group. I copied that from video. In the this code works, but my code not. What can I do with that? -
How to sign in to pyrogram (Client) with django instead of interactive console?
I want to create useful telegram utils for my own. The first big problem is signing into pyrogram Client (Telegram account) I did somethings in django. I've tried to login like that but I've got an error. Here is my view of django: def add_telegram_account(request): code_sent = False phone_number = '' client_sign_in_info = {} two_step = False if 'phone' in request.GET: phone_number = request.GET['phone'] client = Client(phone_number, api_id=api_id, api_hash=api_hash) client.connect() client_sign_in_info = client.send_code(phone_number=phone_number) code_sent = True if request.method == "POST" and 'code' in request.POST: code = request.POST['code'] try: client.sign_in(phone_number, client_sign_in_info.phone_code_hash, code) client.send_message("me", "logged in") except SessionPasswordNeeded: two_step = True if request.method == "POST" and 'two_step' in request.POST: client.check_password(request.POST['two_step']) client.send_message("me", "logged in") return render(request, "telegram/add_telegram_account.html", {'code_sent':code_sent}) And I've got this error --> There is no current event loop in thread 'Thread-1 (process_request_thread)'. -
Using Django paginator to display multiple Django forms page by page but unable to save the data from the pages
I am using Django paginator to create an input page that display multiple forms as single pages. With the paginator in place i would like to enable endless scrolling. I have asked questions to ChatGPT and so far the code provided does not save the data. The latest solution does not even show the save all button as intended. I am not sure if the data is actually stored in the session before changing to the next page as every time i change page, the form is blank. below is the view function and html template. The generation of the page with the correct sub template is working. `# views.py from django.core.paginator import Paginator from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from django.contrib.auth import authenticate, logout from django.contrib import messages from django.http import JsonResponse, HttpResponseRedirect from django.forms.models import model_to_dict from django.db import transaction ... # Define a function to handle the final save operation def save_all_forms(form_classes, form_data_list): # Start a database transaction with transaction.atomic(): # Save the first form instance first_form_class = form_classes[0] first_form_instance = first_form_class(**form_data_list[0]).save() # Save subsequent form instances instances = [first_form_instance] for form_class, form_data in zip(form_classes[1:], … -
404 1804 error when using Django template and trying to get Javascript located in static folder
I am working in a Django template and getting the error 404 1804 when trying to get a javascript script located inside the static folder. Here is my javascript code, file name is current_time.js, located inside the static folder. const displayTime = document.querySelector(".display-time"); // Time function showTime() { let time = new Date(); displayTime.innerText = time.toLocaleTimeString("en-US", { hour12: false }); setTimeout(showTime, 1000); } showTime(); Here is my Django template {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Personal Page</title> </head> <body> <div class= "heading-container"> <h1> Hi Thien </h1> </div> <div class="container"> <link rel="stylesheet" href="{% static 'style_time.css' %}"> <div class="display-date"> <h1>{% include 'personal_page_app/datetime.html' with date_time=date_time %}</h1> </div> <div class="display-time"></div> <script src="{% static 'current_time.js' %}"></script> </body> </html> and here is the error shown in the terminal (only js file, I can still get CSS to work) "GET /static/current_time.js HTTP/1.1" 404 1804 -
celery can not conect to redis in docker
i set all confing and see all question in stackoverflow but celery can not conect to redis and i get this error when i run docker-compose up in pycharm termal. consumer: Cannot connect to redis://127.0.0.1:6379/0: Error 111 connecting to 127.0.0.1:6379. Connection refused.. this is my docker-compose i try to connect all servis to main network. version: '3.3' services: redis: image: redis:7.2-alpine3.18 networks: - main db: container_name: postgres image: postgres:16 environment: - POSTGRES_DB=shop - POSTGRES_USER=comiser - POSTGRES_PASSWORD=Hosein67 networks: - main ports: - "5432:5432" restart: always volumes: - shop-data:/var/lib/postgresql/data app: build: context: . command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: app ports: - "8000:8000" volumes: - ./src:/src - ./data/web:/vol/web depends_on: - db restart: always networks: - main celery: container_name: celery command: celery -A shop worker -l INFO depends_on: - db - app - redis links: - redis build: context: . networks: - main networks: main: volumes: shop-data: this is my celery.py. i try best practic to confing celery from celery import Celery from datetime import timedelta import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.envs.development') app = Celery('shop', broker='redis://redis:6379/0') app.autodiscover_tasks() app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.result_backend = 'rpc://' app.conf.task_serializer = 'json' app.conf.result_serializer = 'pickle' app.conf.accept_content = ['json', 'pickle'] app.conf.result_expires = timedelta(days=1) app.conf.task_always_eager = False … -
How to generate an unique id for each Component of initial value of useState()
I want to create 30 empty Taskcard components at the beginning of the state my problem is that each taskcard has import React from 'react' import { useEffect, useState } from 'react' import { getTasks } from '../api/task.api' import { TaskCard } from './TaskCard' export function TaskLists() { const [tasks, setTasks] = useState(Array(30).fill({id: 1, title: 'title', description: 'description'})) useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data) setTasks(res.data); } loadTasks(); },[]); const removeTask = (id) => { setTasks(tasks.filter(task => task.id !== id)); } return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} onDelete={removeTask} /> ))} </div> ) } the same id how can I fix that? -
Is it possible to use variable in meta tag?
I am new at web dev. I am using Django, and I just wonder is it possible to use variable in meta description tag, Just like this: <meta name="description" content="{{blog_detail.context_1|slice:160|safe}}"> Will it still appear on search engines? -
Django: How to get an element from list by using index on templates?
This is my current code: {% for question in model.get_questions %} {% with counter=forloop.counter %} {{ question }} {{ model.get_fields.counter }} <br> {% endwith %} {% endfor %} When I only print counter it works, when I type any number instead of model.get_fields.counter but in this way that I do does not works. What should I do? -
How can i send data back to Vue/Quasar with Django?
Im currently working on a project that used a Django backend with a Vue/Qasar front ends. I am able to make a POST request to Django using CORS, but I cannot figure out how to send data back to the frontend. I have it so that each vue page makes a post request to say send login information to django. django takes the json format in the views.py page as a request and sends it to the database to call the users profile information. Once i get the data back i don't know how to target my front-end. Django is running on localhost:8000 while vue is running on localhost:9000.[python back end](https://i.stack.imgur.com/tBItJ.png) I tried looking if there is a way to issue an httpresponse or jsonresponse so that it takes in a parameter to a different url in this case localhost:9000, but can't find anything. I also tried to see if maybe the request carries information on the url making the request as to make a direct response, but my response is being sent to localhost:8000 instead. -
Problem with my state when deleting a component
Here is my api file: import axios from "axios"; const taskApi = axios.create({ baseURL: "http://localhost:8000/tareas/api/v1/tareas/", }); export const getTasks = () => taskApi.get("/"); export const createTask = (task) => taskApi.post("/", task); export const deleteTask = (id) => axios.delete(`http://localhost:8000/tareas/api/v1/tareas/${id}/`); now here is the component that displays all of my tasks: import React from 'react' import { useEffect, useState } from 'react' import { getTasks } from '../api/task.api' import { TaskCard } from './TaskCard' export function TaskLists() { const [tasks, setTasks] = useState([]) useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data) setTasks(res.data); } loadTasks(); },[]); return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} /> ))} </div> ) } and here is my TaskCard component that is causing the error: import React, { useState } from 'react' import { deleteTask } from '../api/task.api' export function TaskCard({task}) { const [tasks, setTasks] = useState([]); const handleDelete = async (id) => { await deleteTask(id); setTasks(tasks.filter(task => task.id !== id)); } return ( <div> <h1>{task.title}</h1> <p>{task.description}</p> <hr/> <button onClick={() => handleDelete(task.id)}>Delete</button> </div> ) } I am getting the error : settle.js:19 Uncaught (in promise) When I press the delete button I want that the task card immediately gets deleted from the … -
Wagtail CheckConstraint, column live does not exists
I have such model from wagtail.models import Page class Article(Page): price = PositiveIntegerField( null=True, blank=True, ) class Meta: constraints = [ CheckConstraint(check=Q(price__gte=100) & Q(live=True), name="min price for published"), CheckConstraint(check=Q(price__lte=350000) & Q(live=True), name="max price for published"), ] After running makemigrations everything is fine. But when I try to execute it I got an error django.db.utils.ProgrammingError: column "live" does not exist How could that possible be? live column is part of Page. How this can be fixed? -
How to resolve Horn clause-like tag implications with Django and Postgres database
I am creating a content system with Django where users can create and publish content. Each document created by the user can have multiple tags. I am designing a tag implication system where some tags can imply the presence of other tags. For a simple example, assume "color" and "red" are tags. The following implication exists: "red" implies "color". When a user tags their document with "red", it also has a "color" tag added automatically. Implications are global and apply to every user and document. What I want to do is make tag implications more powerful, I would like to make it possible to require the presence of multiple tags to imply another tag, like a Horn clause. For example, I want an implication where the presence of "red" and "blue" implies the tag "multiple_colors". This could be written Horn clause-like: "red", "blue" -> "multiple_colors". Using Postgres and Django to implement tag implication resolution where only a single tag can imply a tag is simple to implement. You simply have a Django model: class Tag(Model): name = CharField() class TagImplication(Model): antecedent = ForeignKey(Tag) consequent = ForeignKey(Tag) To resolve all implied tags given a set of tags requires an iterative approach. … -
how to make the possibility of adding products to cart for anyone even for non authorized people
when i try to add the product to cart as guest i get this error: Page not found (404) No Session matches the given query. Request Method: POST Request URL: http://127.0.0.1:8000/store/la-fleur-fily-suvignuion/ Raised by: shop.views.Product Using the URLconf defined in lafleurlily.urls, Django tried these URL patterns, in this order: admin/ [name='home'] about/ [name='about_us'] near_me/ [name='find_near_me'] contact-us/ [name='contact_us'] store/ [name='all_products'] store/ category/wines/ [name='wine_category'] store/ category/sparkling/ [name='sparkling_category'] store/ <slug:wine_slug>/ [name='each_wine'] The current path, store/la-fleur-fily-suvignuion/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. orders/views.py: class CartPage(View): template = 'orders/cart.html' def get(self, request): session_key = request.session.session_key session = get_object_or_404(Session, session_key=session_key) cart = get_object_or_404(Cart, session=session) items = CartItem.objects.filter(cart_items=cart) def item_total(): summ = 0 for each in items: print(each.product.price, each.quantity) summ = summ + each.product.price * each.quantity return float(summ) context = { 'cart': cart, 'item': items, 'item_total': item_total() } return render(request, self.template, context) shop/views.py: class Product(View): #SubscribePost, template = 'shop/product.html' model = Wine def get(self, request, wine_slug): product = get_object_or_404(self.model, slug=wine_slug) context = {'wine': product} return render(request, self.template, context=context) def post(self, request, wine_slug): action = request.POST.get('action') if action == 'add_to_cart': return self.add_to_cart(request, wine_slug) def … -
Streaming not working when adding uwsgi in between python ngnix
I'm developing a chat application that streams messages, and it functions well when I access the UI directly through Django on my local environment. It also works when I have the following setup: Python server <-> Nginx However, when I introduce uWSGI into the configuration, the response streaming stops, and I receive the response all at once. I've tried various solutions, but none have resolved the issue. Can you provide guidance on how to correct this problem? Python server <-> uwsgi <-> Nginx Streaming should work as expected. I tried to reduce buffer but didnt work -
Django: Fields as list element in models
Actually I don't know if its possible but this is a rough example of what do I want its like, class ImAModel(models.Model): field_of_list_of_questions = (models.BooleanField(), models.BooleanField(), models.BooleanField()) I need this beacuse I will have a model that have a vary field. And also there may be a lot of fields in it. Then I want to call them like this val = model.field_of_lists_of_questions[1] It'll be very enjoying if it's possible. -
All channels in a group
I used redis as a channel layer in a project . Now i want to access all the channels in group . How can i achieve this without using database . I just want to iterate over group . CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [ # (REDIS_HOST, REDIS_PORT) , (os.getenv('REDIS_URL'), os.getenv('REDIS_PORT')), ], }, }, } Is it possible when redis is used as channel layer . -
CSRF cookie not set. Django auth
Here is my "login" function that I am using to authenticate users when they provide their credentials in NextJs website fronend: export const login = (username, email, password) => async dispatch => { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); console.log(csrftoken); const config = { headers: { 'Content-Type': 'application/json', } }; const config_two = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, } }; console.log(config_two) const body = JSON.stringify({ email, password }); const body_two = JSON.stringify({ username, password }); try { const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config); const res_two = await axios.post(`http://localhost:8000/api-token-auth/`, body_two, config_two); dispatch({ type: LOGIN_SUCCESS, payload: res.data }); dispatch(load_user()); toast.success("You are logged in"); } catch (err) { toast.error("Something went wrong"); dispatch({ type: LOGIN_FAIL }) } }; For one purpose I had to include another post request to get tokens from the database which are …