Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the recommended settings in a Django project that uses firebase as the database?
What are the recommended procedures if my Django project uses firebase-google as the main database? It is relatively simple to import data from firebase, however Django is already configured for sqlite, is it necessary to make any changes related to this? Currently I only import firebase libraries and configuration files according to documentation, but I don't do makemigrations for example. Although the project works, I would like to understand the implications of working this way. -
How to test dependent Django API endpoints in isolation?
I'm working on a Django project with two API endpoints that operate in tandem. Here's the flow: The first API endpoint modifies some data, or maybe creates new records, and then it returns certain information. This returned information from the first API is then used as input to call the second API endpoint. I've been able to write a test for the first API endpoint without any issues. However, when it comes to the second API endpoint, I'm at a crossroads: Should I call the first API within the test of the second API to get the required information? (This feels like it's breaking the isolation principle of testing.) Or, should I replicate the state or environment using fixtures/mocks so that I can directly test the second API without the actual call to the first API? I'd appreciate insights on the best practices for this scenario. Is there a standard or recommended way of handling such situations in Django testing? -
Python web development
May I know what utility or package should I use to get web analytics of web site just like shopify. I would like to see which categories, products and blogs are being read more or clicked more. How much is the time spent by each person on those links ? Steps to achieve that functionality -
Django database-dependent one-time initialization
In my Django app, I have a routing.py helper module with a get_route function that is used by my app. Before I can call this function, I need to build a graph network, which is slow (seconds), so I want to do this once instead of on every get_route call. I build my graph network based on data in my database, so I need to access models (read-only) during this initialization. This question is similar but as pointed out there, the accepted answer is wrong, since it relies on django's AppConfig.ready(), but as is pointed out in the docs, if you make database queries in there, they will access your production database instead of your test database when running tests. Is there a way to do one-time initialization after Django has loaded the database? -
I want to display user image on my index.html {{ user.UserProfileInfo.profile_pic.url }}
Here is my models.py and here is how i tried to use it in my index.html I'm ready and willing to upload any other snippet of my code if needed. any help will be greatly appreciated thanks in advance I'm trying to display the user's image on my index.html template -
Dockerized django taking long time for build the docker-compose
I'm running a dockerized Django application: only Django + Postgres on local. When I start the application and go to any localhost URL, it takes up to 20-30 minutes to build. Here is my dockerfile: FROM python:3-alpine LABEL maintainer="joyalcs2@gmail.com" ENV PYTHONUNBUFFERED=1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Here is my docker-compose.yml: version: "3.11" services: app: build: context: . args: - DEV=true ports: - "8000:8000" image: app:django container_name: rest_container volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" requirements.txt: Django == 4.2.4 djangorestframework == 3.14.0 psycopg2 == 2.9.7 drf_spectacular == 0.26.4 I tried many times and i changed the image many time .but it takes so much time.Also, i used -
Submit a form with Fetch to a Django View
I'm a beginner trying to figure how to use both Django and Fetch api. I was trying to follow this question Django - taking values from POST request, JavaScript fetch API To figure out how to POST a form to a Django view, and access the data from the view. I'm not sure if my header has an issue. my html form <form class="basicform"> <label for="nametextbox">Change First Name</label> <input type="text" name="nametextbox"> </form>` My fetch POST request function postForm(id, form){ var formData = new FormData (form); let response = fetch("{% url 'fetch-ppl' '12345' %}".replace('12345',id), { method: 'POST', body: formData, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "X-CSRFToken": getCookie("csrftoken") }, }) .then(response => response.json()) .then(data=>{ console.log(data); }) return 'Post Done'; } My POST view, that I'm trying to send the form data to def post_form_rest(request, pk): ppl = PersonalData.objects.get(id=pk) serializer = PersonalDataSerializer(ppl,many=False) if (request.POST): print("It's a Post Request") print(request.POST); data = ["post request done"] return JsonResponse(data) return JsonResponse(serializer.data) My problem is when I send my POST request, the django view doesn't detect any POST data at all, it just skips to the end where it gives me a json response of the initial model object. (I don't get any print statements … -
Kubernetes: Secrets update but server not rolling out with new env values
I've a Kubernetes cluster running Django on DEBUG=True using ConfigMap and some other secrets using K8's secrets. The problem I'm having is that even if I rollout the server it keeps having debug true values, and when I inspect the container, the env shows that it's in False. Any idea why this is happening, and how to solve it? -
Django shows Internal Server Error in Production while uploading images
My django application shows internal server error when I try to upload images in the production server when I turn the debug = False and it works well when debug = True. I'm using django-imagekit for processing the images. I'm using Whitenoise to server my media and static files. Here is my code: setting.py STATIC_URL = '/static/' MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py image = ProcessedImageField(upload_to='authors', format='JPEG', options={'quality': 60}) I hosted the site on Vercel -
Django Grappelli 3.0.7 radio_fields admin.HORIZONTAL not working
Upgraded to Grappelli 3.0.7 with Django 4.0.10 and radio fields are stacking vertically even though specified as radio_fields = {'show_weekends': admin.HORIZONTAL, 'group_by_dept': admin.HORIZONTAL} If I comment out Grappelli in INSTALLED_APPS, they work properly so it's not a Django issue -
Migrations in FastAPI libs?
In Django it is quite convenient that 3d party libs could store their own models and migrations. F.e. django-celery-beat - it has functionality which require database table. It is also convenient to have single settings object from which 3d party libs could get necessary settings. But what about FastAPI? How 3d party lib could say a user which settings it needs? How to provide a user functionality which requires a database table? -
Why CSS works with "python manage.py runserver" but not with Gunicorn?
When I run, from the command line, python manage.py runserver mywebsite.com:8099 the css works fine. But when I use the systemd service with Gunicorn socket, the app works but without the css. Even if I use the following command: gunicorn demo.wsgi:application, the app works fine but without the css. Excerpt from my settings.py: STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "mystaticfiles" ] Excerpt from my nginx config file: location /static/ { root /root/djdeploy/demo/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } My Django project working directory is: /root/djdeploy/demo/, I have put my css files in the following folder: /root/djdeploy/demo/mystaticfiles -
Error Django - SQL Server near "EXEC": syntax error
I have a problem calling Stored Procedured in Django, can you please help, below is the error: My funtion view def homeKTA(request): cursor = connection.cursor() try: cursor.execute("EXEC dbo.processos") result = cursor.fetchall() finally: cursor.close() return render(request, "homeRCKTA.html", result) yes that's exactly what is expected -
Revoke/replace Celery tasks under certain conditions
Let's say I've got a class Foo and a function which can be called like that: calculate(foo, dt) (the first argument is an instance of Foo, the second a datetime.datetime instance). Also, calculate updates various things related to foo in a database, calculate is decorated with @transaction.atomic to avoid reaching an inconsistent state in case of issue, behind calculate lies a recurrence relation, running it is computationally expensive, this is one of the reasons why it's called through a Celery task, when dateX > dateY, running calculate(foo, dateX) is pointless if you know you'll have to run calculate(foo, dateY) anyway, because the set of values updated by calculate(foo, dateX) is included in the set of values updated by calculate(foo, dateY). Now, how to run calculate as often as necessary without unnecessary calculations? In other terms, I think I'm looking for a function schedule_calc, taking 2 arguments foo and dt (like calculate), also matching the following requirements: when there isn't any task related to foo, a new one is created which will eventually run calculate(foo, dt), when there is such a task which will eventually run calculate(foo, date1), let's call it T1, several possible outcomes: if date1 <= dt and T1 … -
How to upload mutiple images in the django admin
It involves uploading multiple images to the django admin and the only one should show in the listings.html , and then in that instance post the other images should display there . I have done majority of the work to ensure the post is saved. Please bear in mind that i use an html page (pro.html) where i have the form my users will input whatever they want to post . Once the post in submited , it is automatically saved in the django admin . Amongst the form i require 8 images . The thing now is, if i upload 8 images it is going to save 8 times instead of once. This is my views.py from django.conf import settings from django.conf.urls.static import static from .forms import PostForm from django.shortcuts import render, get_object_or_404 from .models import Post, PostImage from django.http import HttpResponse # Create your views here. def post_create(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() for file in request.FILES.getlist('image'): image = Image(image=file) image.save() else: form = PostForm() return render(request, 'estateapp/pro.html', {'form': form}) def home(request): return render(request, 'estateapp/home.html') def Listings(request): posts = [] for post in Post.objects.all(): post = { 'title': post.title, … -
Django Management Command Triggers URLs When Checking Database Connection
I've encountered an unexpected behavior while working on a Django project involving a custom management command. The command I've created, named wait_for_db, is intended to test whether the database connection is ready before proceeding with other tasks. However, when I trigger this command using python manage.py wait_for_db, it seems to be invoking some URLs, leading to database-related errors. I've structured the management command to primarily check the database connection's readiness without interacting with URLs or the web server. The goal is to ensure that the database is available before proceeding with other operations. Here's a simplified version of my management command: """ Django command to wait for the database to be available. """ import time from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to wait for database.""" def handle(self, *args, **options): """Entrypoint for command.""" self.stdout.write('Waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except (Psycopg2OpError, OperationalError): self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) Despite my best efforts, when I execute python manage.py wait_for_db, it seems to trigger some URLs or components that access the database. As a result, I receive errors indicating that … -
Django static and media files in production
I've deployed my first django ( learning ) project to a hosting server. I turned "DEBUG" off and run "collectstatic" so I have "static" and "media" folders in my main directory ( besides "manage.py" and ... ). But static and media files are not accessible unless I move the their folders to "public-html" directory every time. How can I change my root directory from "public-html" to "social" (main django folder). And does this fix the problem? Note: In my cpanel there is no apache configs available in etc folder. I asked the hosting provider to change the root directory for me but they said it can be done by me through some .htaccess configs. I added this to .htaccess file: RewriteEngine On RewriteCond %{HTTP_HOST} ^sadeqmousawi.ir [NC] RewriteRule ^(.*)$ /social/$1 [L] But it didn't work. -
Edit Django Admin JS Sheet Element
I am using this js form to select users: <style> .selector { float: none; display: block; height: 330px; } .selector-available, .selector-chosen { float: left; width: 380px; height: 330px; text-align: center; margin-bottom: 8px; } .selector ul.selector-chooser { float: left; width: 22px; height: 330px; background-color: var(--selected-bg); border-radius: 10px; margin: 10em 5px 0 5px; padding: 0; } .selector input[type="submit"] { display: block; clear: both; } .selector h2 { font-size: 15px; } textarea { display: block; width: 450px; } </style> Which results in a page rendering: I am trying to put the remove all button as well as the directional arrows between the Available users and Selected Users boxes so everything is even but, I am not sure how to do so. Could someone point me in the right direction? -
Prevent LDAP users from being automatically created in the Django admin site
I setup an LDAP authentication to login to a Django admin site from an active directory(AD) After logging in, the user are populated in the Users of Django admin site. Is there a way to prevent that the users are populated in the Django admin site? I though that AUTH_LDAP_USER_ATTR_MAP is what populates the user but I removed it and the users are still populated after logging in. Here is the settings.py import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesTypes, LDAPGroupQuery AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend' ] AUTH_LDAP_SERVER_URI = "ldap://server.name" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_BIND_DN = "cn=user,ou=group,dc=example,dc=example" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_REFERRALS : False } AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=example,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "ou=group,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=group)" IS_STAFF_FLAG = ( LDAPGroupQuery("cn=group,ou=group,dc=example,dc=com") | LDAPGroupQuery("cn=group,ou=group,dc=example,dc=com") ) AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_staff': IS_STAFF_FLAG, 'is_superuser': "cn=group,ou=group,dc=example,dc=example" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 -
Relation programmingError
I have model code for which migrations have successfully created and passed: from django.db import models from django.contrib.auth.models import AbstractUser class Employee(AbstractUser): probation = models.BooleanField(default=False) position = models.CharField(max_length=50, blank=True) groups = None user_permissions = None class Order(models.Model): name = models.CharField(max_length=100) description = models.TextField() employee = models.ForeignKey('employee', on_delete=models.CASCADE) def __str__(self): return self.name after which I registered them in the admin panel from django.contrib import admin from .models import Employee, Order @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'probation', 'position') list_filter = ('probation', 'position') search_fields = ('username', 'first_name', 'last_name', 'email') @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ('name', 'employee') list_filter = ('employee',) search_fields = ('name', 'employee__username', 'employee__first_name', 'employee__last_name') then when I try to add a new employee through the admin panel, I get an error relation "main_employee" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "main_employee" ^ Please tell me what is wrong with my code, I will be grateful -
Statistic on Django admin Index page
I know that Django admin main page is in index.html. I want to change this page, and add some statistic things, like last 5 errors from DB. My question is: that it is possible, create model for main admin page and show in there some information like I can when I will create some custom models and views? Do you have some example for that somewhere ? -
How to schedule a function in aiogram
I have Django+aiogram bot and that's how my mailing works: Manager/admin create a instance of the Post/Poll model in the admin panel -> Admin approve/disapprove it in telegram PM with inline keyboard -> if approves ("post" callback data) -> do_mailing function immediately works But I added the "scheduled_time = models.DateTimeField" field in my Post/Poll models and I want do_mailing function to work in that scheduled_time once, without repeats. Post model: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Менеджер') text = models.TextField(verbose_name='Текст') scheduled_time = models.DateTimeField(blank=True, null=True, verbose_name="Дата и время рассылки") approved = models.BooleanField(default=False, verbose_name='Подтверждён') total_media_count = models.PositiveIntegerField(default=0, verbose_name='Сколько фотографий загрузите?') group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Группа пользователей бота') created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name='Создано') There's a handler for "post" callback data which works after admin's approval: @dp.callback_query_handler(lambda query: query.data == 'post', state="*") async def post_handler(callback_query: CallbackQuery, state: FSMContext): admin = callback_query.message['chat']['id'] message = callback_query.message.text.split('\n') await change_post_status(message[0].split(': ')[1]) await do_mailing(message) logging.info(f"Пост {message[0].split(': ')[1]} был одобрен на рассылку админом") await bot.send_message(chat_id=admin, text=f"Рассылка поста {message[0].split(': ')[1]} одобрена!") await bot.send_message(chat_id=message[-1].split(': ')[1].split(' ')[0], text=f"Рассылка поста {message[0].split(': ')[1]} одобрена!") So do_mailing function is what I need to schedule. I can get "scheduled_time" field from the "message" variable, so don't think about it, let's just say … -
Understanding TemplateDoesNOtExist at home.html
I am working on django for beginners and the code provided does not work. I have copied and pasted after manually typing it in and the error persists around this class based view. It claims that home.html does not exist. The file certainly does. There is an odd home = value in the code that I do not understand why it is there as it is outside the norm. However I clearly see the hashtag # new which means to include the new code. I tried the extra removing home= and a red squiggly line immediately appeared as an error. The error message reads: Traceback (most recent call last): File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 90, in rendered_content template = self.resolve_template(self.template_name) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/response.py", line 72, in resolve_template return select_template(template, using=self.using) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: home.html Another problem I am experiencing is that I went to a prior commit and github is saying hey, you need to do a pull request on the most … -
Change font color in Django ModelChoiceField widget after selection made
I have styled the font and font color for the select menu in my Django form using the widget. Is it possible to change the font color once a selection is made? For example, select menu text starts off white and after selection is made it turns green. I am using Crispy Form tags on the front end. class FootballLineup(forms.ModelForm): class Meta: model = FootballContestEntry fields = ['qb'] qb = forms.ModelChoiceField(label='', queryset=NFLPlayer.objects.filter(active=True, position='QB'), empty_label="Select Quarterback", required=True) qb.widget.attrs.update({'class': 'text-center lineup-select marker'}) -
Django logging issue on IIS
I'm new to Django and IIS server. I have a web server deployed with IIS, and I'm encountering an issue with the code. I'd like to try fixing it on my own, but I don't have a console (like in development mode) to show me what's going on. So, I started trying the logging functions in settings.py. Here's my configuration FORMATTERS = ({"verbose": {"format": "{levelname} {asctime:s} {name} {threadName} {thread:d} {module} {filename} {lineno:d} {name} {funcName} {process:d} {message}","style": "{",},"simple": {"format": "{levelname} {asctime:s} {name} {module} {filename} {lineno:d} {funcName} {message}","style": "{",},},) HANDLERS = {"console_handler": {"class": "logging.StreamHandler","formatter": "simple","level": "DEBUG"},"info_handler": {"class": "logging.handlers.RotatingFileHandler","filename": f"{BASE_DIR}/logs/blogthedata_info.log","mode": "a","encoding": "utf-8","formatter": "verbose","level": "INFO","backupCount": 5,"maxBytes": 1024 * 1024 * 5, # 5 MB},"error_handler": {"class": "logging.handlers.RotatingFileHandler","filename": f"{BASE_DIR}/logs/blogthedata_error.log","mode": "a","formatter": "verbose","level": "WARNING","backupCount": 5,"maxBytes": 1024 * 1024 * 5, # 5 MB},} LOGGERS = ({"django": {"handlers": ["console_handler", "info_handler"],"level": "INFO",},"django.request": {"handlers": ["error_handler"],"level": "INFO","propagate": True,},"django.template": {"handlers": ["error_handler"],"level": "DEBUG","propagate": True,},"django.server": {"handlers": ["error_handler"],"level": "INFO","propagate": True,},},) LOGGING = {"version": 1,"disable_existing_loggers": False,"formatters": FORMATTERS[0],"handlers": HANDLERS,"loggers": LOGGERS[0],}` taken from this explaination [https://www.youtube.com/watch?v=m_EkU56KdJg ](here): this code generates 4 files: blogthedata_detailed.log blogthedata_error.log blogthedata_info.log the detailed.log contains this:INFO 2023-08-25 11:53:47,710 Thread-1 (process_request_thread) 8792 basehttp basehttp.py 212 django.server log_message 12856 "GET /static/js/login_script.js HTTP/1.1" 200 751INFO 2023-08-25 11:53:47,780 Thread-2 (process_request_thread) 20080 basehttp basehttp.py 212 django.server log_message 12856 "GET /static/js/jQuery.js HTTP/1.1" …