Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ModuleNotFoundError. No module named 'myApp'
I am using termux I created a virtual environment, started django project, cd into the second directory of my project, and started an app. Here is the arrangement of my dir. and files I added the app to the INSTALLED_APP in setting.py INSTALLED_APPS in settings.py When I run 'python manage.py runserver, I get an error: ModuleNotFoundError. No module named 'myApp_name' Error message after running 'python manage.py runserver' Please help me resolve this issue. I am a beginner and have been on this for two days I am stuck and can't learn further. I expect 'python manage.py runserver' to run without an error, since I started an app and added its name to INSTALLED_APP -
How to run celery in django from docker
I learn docker and don't understand why celery can't connect to rabbitmq. I've created 2 images for rabbitmq and django, here is my docker-compose: version: "3.0" services: # WEB django: build: . volumes: - media_volume:/website/journal_website/media - static_volume:/website/journal_website/static - database_volume:/website/journal_website/database ports: - "8000:8000" depends_on: - rabbit # RabbitMQ rabbit: hostname: rabbit container_name: rabbitmq image: rabbitmq:3.12-rc-management environment: - RABBITMQ_DEFAULT_USER=simple_user - RABBITMQ_DEFAULT_PASS=simple_password ports: # AMQP protocol port - "5672:5672" # HTTP management UI - "15672:15672" restart: always volumes: media_volume: static_volume: database_volume: my broker configuration in settings.py in django: CELERY_BROKER_URL = 'amqp://localhost:5672' celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") celery_application = Celery("website") celery_application.config_from_object("django.conf:settings", namespace="CELERY") celery_application.autodiscover_tasks() entrypoint.sh that's used as entrypoint in Dockerfile: #!/bin/bash # Start Celery celery -A website worker -l info # Run Django server python3.11 manage.py runserver 127.0.0.1:8000 and Dockerfile: # Many many commands to install python and all dependencies in ubuntu 20.04 # Run Django server EXPOSE 8000 ENTRYPOINT ["/entrypoint.sh"] I use Docker Desktop on Windows 10, when I run docker compose up or run container in desktop application I get such error: [Date: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused., I've checked that localhost is 127.0.0.1. What should I … -
Django: Implementing a dependent dropdown list in a form
Hello StackOverflow community! I am new to programming and am currently working on a Django-based website for ITSM ticket management. My site has two main components: A ticket manager that displays created tickets, their status, address, assigned technician, problem description, etc. An administrative part in Django, which only certain users have access to. I am having trouble implementing a ticket creation or update form. I am trying to implement a dependent dropdown list functionality: when a district is selected in the ticket creation form, only a list of technicians associated with that district should be displayed in the "Technician" field. I am unsure of how to correctly implement this functionality. Maybe I should use JavaScript or AJAX, or is there a way to do this directly in Django? Your guidance or pointers would be highly valuable. Thank you for your assistance! **models.py** `from django.db import models from django.utils import timezone from django.utils.formats import date_format from django import forms class Ticket(models.Model): STATUSES = ( ('new', 'Новый'), ('in_progress', 'В работе'), ('overdue', 'Просрочен'), ('deferred', 'Отложенный') ) DEVICE_CHOICES = [ ('Выберите тип прибора', 'Выберите тип прибора'), ('Stemax', 'Stemax'), ('Приток', 'Приток'), ('Болид', 'Болид'), ('Альтоника', 'Альтоника'), ] title = models.CharField(max_length=200, default='Default Title') # Добавлено новое поле … -
Cache API for requested ID for specific time / Django admin filter
I'm learning python for few weeks and I'm creating hockey app. I have two problems. text In this API we have about 1000 players with specific ID. I know how I get specific value and how I create for loop for all values, but I don't want send request for all players (ofc) and store this values in a database or send request every time when some app user want it. So when user send request for example for Ovechkin, for McDavid..., how I could cache this for some time because data should be updated - if they play another match? Should I do something in Redis or django-cache? I created models in Django - Team, League, Fixture. I added teams and assign them League(NHL, SHL, DEL etc.) and for fixture? I chose league NHL and saw all teams(included from Germany, Sweden) still. How I can create live filter in Django Admin when I click on NHL = all non-NHL teams disappear. class League(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Team(models.Model): name = models.CharField(max_length=128, unique=True) league = models.ForeignKey(to=League, on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Fixture(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='fixtures') home_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_games') away_team = … -
Django NoReverseMatch - content doesn't load properly
I have a blog app in my Django project that is based on this tutorial. With the link to the blog placed in my main.html template, the site throws a NoReverseMatch error. I can't seem to figure it out. Here's the HTML: <li class="nav-item"><a href="{% url 'blog' %}" class="nav-link" id="header">Blog</a></li> Here's the urls.py code: from django.contrib import admin from main import views from django.conf.urls import include from django.urls import path from main.views import dashboard, register, about, blog from django.conf import settings from django.conf.urls.static import static app_name = 'main' urlpatterns = [ path('', views.main, name='main'), path('admin/', admin.site.urls), path('dashboard/', dashboard, name='dashboard'), path('accounts/', include('django.contrib.auth.urls')), path('register/', register, name='register'), path('about/', about, name='about'), path('blog/', include('blog.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here's the other urls.py: # main/urls.py from django.urls import path, include from main.views import dashboard, register app_name = 'main' urlpatterns = [ path('blog/', blog, name='blog'), ] Here's the views.py code: # main/views.py from django.http import HttpResponse from django.contrib.auth import login as auth_login from django.shortcuts import redirect, render from django.urls import reverse from main.forms import CustomUserCreationForm # Create your views here. def main(request): return render(request, 'main.html', {}) def dashboard(request): return render(request, 'users/dashboard.html') def admin(request): return render(request, 'admin') def login(request): return render(request, 'registration/login.html') def register(request): if request.method == 'GET': … -
combine values with select_related
I have to models "Product" and "user" and post model has user foreignKey I want to query posts join with user with only ("username","name) fields I tried to use Product.objects.values('id', 'title',"user__username","user__name") and i got { id, title, username, name } but i want something like this { id, title, user:{ username, name } } -
How to avoid Graphene sorting an OrderedDict on query response? (Python, Django)
I am trying to return a dict of OrderedDicts from a Graphene endpoint in a Django application, by using the GenericScalar type field. The OrderedDicts are sorted based on value, but the API seems to re-sort the dicts by key. The OrderedDicts items format is: { id : [name, amount] } Example of one of the OrderedDicts that I send: { 'foods': { 3: ['apple', 5], 1: ['banana', 7], 2: ['carrot', 3] }, 'animals': { 5: ['cat', 3], 3: ['dog', 10], 1: ['pig', 5], } } What is received in the endpoint response: { 'foods': { 1: ['banana', 7], 2: ['carrot', 3], 3: ['apple', 5], }, 'animals': { 1: ['pig', 5], 3: ['dog', 10], 5: ['cat', 3], } } I am specifically using OrderedDicts because the order is important, but I have not found a way of avoiding Graphene to re-sort the OrderedDicts by key. This is the how the ObjectType and Query are declared, althought is is nothing out of the ordinary. class DashboardType(g.ObjectType): data = GenericScalar() class Query(object): dashboard = Field(DashboardDataType, id=ID(), date=Date()) def resolve_dashboard(self, info, **kwargs): data = function_to_get_the_data(kwargs) # up until this point the data is still sorted correctly return data The data is sorted as … -
Booking Cycle with Django
I have an app where the user books a session and then pay it using payment service provider (like Fawry or Paymob which are middle-east based companies). the way this is done is when the user books a session or multiple sessions a code is generated and it will be available for say 30 mins. My Question is : should I declare the sessions that the user is going to pay for as booked so when another user fetches the sessions they will not be available to be booked? and if so what happens if the user decided not to pay for the sessions, how would I know? and if I can know and return them back to unbooked status what if the other user that wanted them didn't check for these sessions again? OR should I make them available until the user pay for them then remove them from the available sessions, but then what if two users booked the same session -as it's not yet been removed when one user booked it-, the generated code that they are going to use has an amount of money to be paid it will not check if the session that the … -
How to Merge Byte Files Together in Python
I am running into a situation where I need to generate multiple filled PDF forms, I have the data filled out and the 'bytes' file is accessible, but when I attempt to combine the 2 files in their byte representation, nothing happens, the file is overridden and the original is the only thing shown. What am I doing wrong, this seems like it should be easy. # don't worry about these, they are filled PDFs in byte form, this works as expected. pdf1 = PDFFormManager.fill_with_jinja(file=template, data=data) pdf2 = PDFFormManager.fill_with_jinja(file=template, data={}) # here is the issue print(len(pdf1), len(pdf2)) # 177354 177354 print(type(pdf1), type(pdf2)) # <class 'bytes'> <class 'bytes'> print(len(pdf1+ pdf2)) # 354708 # when I return this, I only get the single pdf, not the concatenated one response = HttpResponse(pdf1+pdf2, content_type=f"application/pdf") -
How to translate simplejwt error (django rest framework)?
What is the best way to translate the error: "No active account found with the given credentials" coming from: from rest_framework_simplejwt.views import TokenObtainPairView ... urlpatterns = [ path('token/', TokenObtainPairView.as_view()), I use React on the frontend and Django and Django Rest Framework on the backend. I changed django settings to: LANGUAGE_CODE = 'pl' but this apparently didn't change the simplejwt error language. -
Django web development pdf [closed]
I want all the pdf to be displayed on the webpage from the database and one can see it from there… The display part is done but whenever i click on a pdf the page loads and gets redirected to the same page and pdf doesn’t open… what should I do? I tried everything but it won’t solve -
I am getting error for Deploying django project on vercel can anyone help me with this
enter image description here i am getting error like this I have tried so many ways to fix it but it didn't help. I think the error must be in selecting the framework preset for Django on Vercel while deploying, I think so. I have selected "OTHER" for Django deployment as suggested on youtube tutorials. -
I am getting raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
My settings.py looks like this and I have created a db with name student in mysql. Despite having installed mysqlclient latest version I am getting this error. I tried with using other database setup but still got similar error. """ Django settings for studentReportCard project. Generated by 'django-admin startproject' using Django 4.2.3. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%38#(h6gd4$$2%n7+-3v3#-n)mcaobie=)1o&f()+&8m!+oq)!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'report_card', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'studentReportCard.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'studentReportCard.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'NAME': 'student', … -
Django crispy_forms using
I have been using crispy_forms for my form on django project. But While Project is running. A problem A problem appears suddenly. how can I solve this problem on my project ? can you help me ? I have to go on this project very faster [[[enter image description here](https://i.stack.imgur.com/x8kr2.png)](https://i.stack.imgur.com/UF8XI.png)](https://i.stack.imgur.com/fDG6k.png) -
Im trying to make a Instagram reel downloader and keep getting this error Expecting "property name enclosed in double quotes: line 1 column 2 (char 1)
Im using django to create a instagram reel downloader but it keeps giving me json errors My code: from django.shortcuts import render , redirect from instascrape import * import json import time # Create your views here. def index(request): if request.method == "GET": return render(request, "index.html") else: if request.POST['url']: google_reel = Reel("https://www.instagram.com/reel/CumvX9VgNQt/?utm_source=ig_web_copy_link&igshid=MzRlODBiNWFlZA==") google_reel.scrape() google_reel.Download(fp = "{path\filename.mp4}") else: return render(request, "index.html", { "error": "Invalid url" }) return redirect("/") The error im getting is "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" im thinking it is a python package problem the one im using is instascrape (https://github.com/chris-greening/instascrape) -
How to send message through django-channels from asyncio loop with add_reader
I am trying to listen for notifications from postgres database and send message through django-channels on each row insertion, for that I want to use asyncio loop, where I am adding reader for connection. However, I am receiving following error on attempt to use async_to_sync: RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. Here is my code: import asyncio import logging import channels.layers from asgiref.sync import async_to_sync from django.conf import settings from django.core.management.base import BaseCommand from django.db import connections channel_layer = channels.layers.get_channel_layer() logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): conns = [(connections[db].cursor().connection, db) for db in settings.DATABASES] loop = asyncio.get_event_loop() for conn, db in conns: conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() cursor.execute("LISTEN event_changed;") loop.add_reader(conn, partial(self.handle_notify, conn=conn, db=db)) logger.info("Starting runlistener loop.") loop.run_forever() def handle_notify(self, conn, db): conn.poll() for notify in conn.notifies: logger.debug(f"new event received on db {db}: {notify.payload}.") async_to_sync(channel_layer.group_send)( db, {"type": "on_new_event", "event": notify.payload} ) conn.notifies.clear() I can't use await in handle_notify since it is not async function and I couldn't find any way to use async function as a callback for add_reader. I've managed to implement this functionality without asyncio, by simply checking connection with select.select in … -
How can fix ' Error: No application module specified.' on DigitalOcean
I am getting ' Error: No application module specified. ' error while I'm trying to deploy my django project. After Successful Build, Digital Ocean is trying deploy it and raise this error after short time. Can you help me about this? Where should I change? settings.py >>> """ Django settings for djcrm project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv # .env dosyasını yükle load_dotenv() DEBUG = os.getenv('DEBUG') # SECRET_KEY'i al SECRET_KEY = os.getenv('SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #third party apps 'crispy_forms', "crispy_tailwind", 'tailwind', #local apps 'leads', 'agents', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djcrm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djcrm.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": … -
Query many to one backward relation Django
I have these 2 models: class User(models.Model): full_name = models.CharField(max_length=255) class WorkSchedule(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) day_of_week = models.IntegerField() start_time = models.TimeField() end_time = models.TimeField() Is it possible for me to use a single query here to get back something like this: { "id": 1, "full_name": "User name", "work_schedule": { { "day_of_week": 1, "start_time": 8:00, "end_time": 20:00 }, { "day_of_week": 2, "start_time": 8:00, "end_time": 20:00 } } } -
Form field not showing in tempate
after defining form field when I try to access in django template using {{form.Date_Joined}} not working class UserAdd(forms.ModelForm): class Meta: model=CompanyUsers fields= '__all__' exclude=['usrPsswd','usrId','usrCmpnyId','lstLogin','is_active','usrDOJ'] widgets={ 'Date_Joined':forms.DateInput(attrs={'type':'date'}), } The widget i've declare not showing <div class="order"> <!-- <div class="head" > --> <h4> ADD COMPANY</h4> <!-- </div> --> <table id="table-datas"> <form method="POST" action=""> {% csrf_token %} <tbody> <tr><td>Username</td><br><td>{{ form.usrNme}}</td></tr> <tr><td>First Name </td><br><td>{{ form.usrFNme}}</td></tr> <tr><td>Last Name </td><br><td>{{ form.usrLNme}}</td></tr> <tr><td>Date of join</td><br><td>{{form.Date_Joined}}</td></tr> <tr><td>Department</td><br><td>{{ form.usrDpt}}</td></tr> <tr><td>Email</td><br><td>{{ form.usrMail}}</td></tr> <tr><td><button type="submit">Register</button></td></tr> </form>``` so the Date Joined field shows nothing -
How to make table editable in django on the clientside
I am building this Django webapp, where I have data stored in the SQLite. And being fetched into a table in the client side. But I have this idea of patching the data from the table itself, just like Edit in grid view, of sharepoint list. Where If I click the toggle button 'editable mode', the all cells become editable and after making necessary changes, if click the toggle button again, the changes should be saved in the database as well. Below are the snippets of the project. views.py class EmployeeUpdateView(View): def patch(self, request, employee_id): data = json.loads(request.body) try: employee = Employee.objects.get(id=employee_id) for change in data: field_name = change['field_name'] field_value = change['field_value'] setattr(employee, field_name, field_value) employee.save() return JsonResponse({'success': True}) except Employee.DoesNotExist: return JsonResponse({'success': False, 'error': 'Employee not found'}) except Exception: return JsonResponse({'success': False, 'error': 'Error saving changes'}) this is url path path('update/<int:employee_id>/', EmployeeUpdateView.as_view(), name='update_employee'), this is the table template <tbody class="thead-light"> {% for employee in page_obj %} <tr style="font-size: 12px;"> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.name }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.phone }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.dob }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.doj }}</td> … -
Wagtail Image Chooser Template returns 404 http not found
When I deploy my wagtail django with nginx and I want to choose an image for a ForeignKeyField to wagtailimages.Image I get a HTTP 404 for <base-url>/cms/images/chooser/ although when I directly access the url it returns the correct json. Is this a nginx Problem or a wagtail / django problem? -
Convert PDF to PDF/A with python
I am working on a Python project and I need to convert a PDF file to PDF/A format programmatically. Ideally, I'm looking for a Python library or tool that supports PDF to PDF/A conversion and provides options to specify PDF/A compliance levels, such as PDF/A-1a or PDF/A-3b. Any example code or a step-by-step guide would be greatly appreciated. I have explored some libraries such as PyPDF2 and pikepdf, but I haven't found a straightforward way to achieve this. Can anyone provide guidance on how to convert a PDF file to PDF/A using Python? -
Django: Rest Framework (Serializer)
I'm new to using the django rest framework. I'm trying to understand how I can validate a field with the serializer based on the input from the user, for example: Serializer: from rest_framework import serializers VALID_REGION = 'region' def validate_region(value): if value != VALID_REGION: raise serializers.ValidationError('Invalid region, make sure region parameter is spelled correctly.') return value class RegionSerializer(serializers.Serializer): region = serializers.CharField(required=False, validators=[validate_region]) Here I want to validate that the region is spelled correctly. views.py def get(request, *args, **kwargs): serializer = RegionSerializer(data = request.data) if serializer.is_valid(): data = serializer.validated_data region = data.get('region', '') regions = region_lib.get_regions(region) return Response({"regions" : regions}, status=status.HTTP_200_OK) else: errors = serializer.errors return Response({"error" : errors}, status=status.HTTP_400_BAD_REQUEST) Here I pass 'regoin' misspelling it intentionally. { "regoin": "Test" } When I run serializer.is_valid() it returns true. Not sure what I'm missing. -
In Django, how to get the return of two functions in the same html page? Error: TypeError: kwargs argument must be a dict, but got function
In Django I have two functions contained in views.py. One is called def city_detail and the other is called def DemoView. Both return return render(request, 'app1/home.html', context). In url.py I would like to use both functions, but it seems I can only use 1 at a time. If I use only one of the two, then it works (only one of the two works). If I write in urlpatterns I write: path('home/', views.city_detail, views.DemoView, name='home'), path('home/', views.DemoView, name='home'), I get the error: raiseTypeError( TypeError: kwargs argument must be a dict, but got function. How can I use both functions in home? -
How to filter the model property value using custom filter in Django admin
I have the model with property and custom filter. Depending on the custom filter value, I need to update the _approved property value (not the model queryset) on the Django admin page. model.py class Model(models.Model): created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Created') updated = models.DateTimeField(auto_now_add=False, auto_now=True, verbose_name='Updated') @property def _approved(self): return ModelRecordRelation.objects.filter(model_id=self.id, status='A').count() admin.py class TimeFrameFilter(SimpleListFilter): title = 'timeframe' parameter_name = 'timeframe' def lookups(self, request, model_admin): return [ ('Today', 'Today'), ('ThisWeek', 'This Week'), ] def queryset(self, request, queryset): return queryset.filter() class ModelAdmin(admin.ModelAdmin): list_display = ['created', 'updated'] class Meta: model = Model def approved(self, obj): return obj._approved approved.admin_order_field = 'approved'