Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Passing values from the forms from one view (one url) to another view (second url) in Django
So I have two forms, and a view which enables users to fill them: def input_view(request): if request.method =="POST": simulation_form = SimulationSettings(request.POST) strategy_form = StrategySettings(request.POST) if simulation_form.is_valid() and strategy_form.is_valid(): simulation_settings = simulation_form.cleaned_data strategy_settings = strategy_form.cleaned_data return render( request, "strategy_simulator/results_view.html", {"simulation_settings": simulation_settings, "strategy_settings": strategy_settings}, ) else: simulation_form = SimulationSettings() strategy_form = StrategySettings() return render( request, "strategy_simulator/input_view.html", {"simulation_form": simulation_form, "strategy_form": strategy_form}, ) With this code, it works and after submitting the forms results_view.html template is displayed properly, but the url does not change and I want results to be under different url. So I've created second view and url to it, but I do not know how to pass forms values from one view to another and then redirect to the url connected to the specific view (results_view in this case). Here is the view: def results_view(request): simulation_settings = request.POST.get('simulation_settings') strategy_settings = request.POST.get('strategy_settings') return render( request, "strategy_simulator/results_view.html", {"simulation_settings": simulation_settings, "strategy_settings": strategy_settings}, ) And here are urls: from . import views from django.urls import path app_name = "strategy_simulator" urlpatterns = [path("results/", views.results_view, name="results_view"),path("", views.input_view, name="input_view"), ] Thanks for help in advance. -
Affiliate marketing in django model
I have a django travel blog, now im looking to find a way to integrate extern city widgets and scripts from my associates inside my articles, what is the best option to do so? I tried in Django CkEditor from Richtextfield(model) in django admin inside scripts to insert the code provided from associated but it's not working at all. -
No module found [my_app] with Apache and mod_wsgi
This is my directory structure, in /var/www: team_django --team_db ---- __init__.py -----settings.py -----wsgi.py My wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'team_db.settings') application = get_wsgi_application() My /etc/apache2/mods-available/wsgi.load: LoadModule wsgi_module "/usr/local/py_ptracker/lib/python3.11/site-packages/mod_wsgi/server/mod_wsgi-py311.cpython-311-x86_64-linux-gnu.so" WSGIPythonHome "/usr/local/py_ptracker" My /etc/apache2/sites-available/vhost.conf: WSGIScriptAlias / /var/www/team_django/team_db/wsgi.py <Directory /var/www/team_django/team_db> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The mod_wsgi is enabled, as the vhost configuration, and everything gets loaded fine. I get this in the error.log though: ModuleNotFoundError: No module named 'team_db' [wsgi:error] [pid 225277] mod_wsgi (pid=225277): Failed to exec Python script file '/var/www/team_django/team_db/wsgi.py'., referer: ... [wsgi:error] [pid 225277] mod_wsgi (pid=225277): Exception occurred processing WSGI script '/var/www/team_django/team_db/wsgi.py'., referer: .... Why isn't the os.environ.setdefault not finding team_db? I've checked all permisions and I also set everything to 777, changing owners and group to www-data or root and all that; to no avail. I can't understand why it's not finding the team_db. Te server runs correctly with Django's runserver and also with the mod_wsgi-express runserver. The mod_wsgi has been built with the same version of Python, within the virtual environment. -
Any Microsoft Dataverse database backend for Django?
I'd like to write a frontend for my Microsoft Dataverse database backend so as to manage Dataverse data easily. Django comes with an easy-to-configure admin which suits my needs fine. I would like to know if there has been any third-party backends for Dataverse already, or I just need to implement the backend by myself because few people care about using Dataverse as the backend for their Django Applications. Craving for your insights! -
how to post an image from react native to django
I'ive been trying to post an image file from react-native but i can't seem to get it right this is the code I tried: const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); if (!result.canceled){ delete result.cancelled; setImage(result.assets[0].uri) } }; and this is the fetch request: const handleSubmit = (name, description, image, email, phone) => { let uri = image.replace("///", "//") var myHeaders = new Headers(); myHeaders.append("Authorization", `Bearer ${userInfo.access_token}`); myHeaders.append("Content-Type", "multipart/form-data"); var formdata = new FormData(); formdata.append("name", name); formdata.append("description", description); formdata.append("photo", uri, uri.split("/").pop()); formdata.append("phone", phone); formdata.append("email", email); var requestOptions = { method: 'POST', headers: myHeaders, body: formdata, redirect: 'follow' }; fetch(`${Url.base}/api/realtor/create-profile`, requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); } this is the error i keep getting: {"photo":["The submitted data was not a file. Check the encoding type on the form."]} -
I'm trying to create multiple user in Django using flags and a custom user model but keep getting something went wrong error
I have created my custom user model with the following code. class UserManager(BaseUserManager): def create_user(self, email, name, phone, password=None): if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) email = email.lower() user = self.model(email=email, name=name, phone=phone) user.set_password(password) user.save(using=self._db) return user def create_vendor(self, email, name, phone, password=None): user = self.create_user(email, name, phone, password) user.is_vendor = True user.save(using=self._db) return user def create_superuser(self, email, name, phone, password=None): user = self.create_user(email, name, phone, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=15, unique=True) otp = models.CharField( max_length=6, ) is_vendor = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name", "phone"] objects = UserManager() def __str__(self): return self.email I have also created my view and i don't know where the issue is in the following code also: class RegisterAPIView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): try: data = request.data print(data) email = data["email"].lower() name = data["email"] phone = data["phone"] password = data["password"] re_password = data["re_password"] is_vendor = data["vendor"] if is_vendor == "True": is_vendor = True else: is_vendor = False if … -
django admin autocomplete filter without foreign key
I have this model: class Person(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) gender = models.CharField(choices=Gender.choices, null=True, blank=True) city = models.CharField(max_length=200, null=True, blank=True) I need autocomplete filter for "city" field https://github.com/farhan0581/django-admin-autocomplete-filter didnt do the job