Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django not showing RAW SQL with sqlmigrate
I'm trying to get the RAW SQL from a migration and it only prints begin and commit. I'm modify a model, adding the middle_name field class User(AbstractBaseUser): email = models.EmailField(max_length=200, blank=False, unique=True) first_name = models.CharField( max_length=200, blank=False, verbose_name="nombre" ) middle_name = models.CharField( max_length=200, blank=True, verbose_name="segundo nombre" ) It creates the migration 0007_user_middle_name.py # Generated by Django 3.2.23 on 2024-06-10 16:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('biglifeapp', '0006_biglifesetting_new_field'), ] operations = [ migrations.AddField( model_name='user', name='middle_name', field=models.CharField(blank=True, max_length=200, verbose_name='segundo nombre'), ), ] but when I run python manage.py sqlmigrate my_app 0007 --database=default it only prints `BEGIN; -- -- Add field middle_name to user -- COMMIT; this should print something like `BEGIN; -- -- Add field middle_name to user -- alter table user add column middle_name (...) COMMIT; I saw 2 questions on stackoverflow, but none of those was the case for this case, the db does indeed change, I'm adding a new column to it For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions? in this case, the --database argument is being provided Django sqlmigrate not showing raw sql -
Telegram mini app with django issue with transferring data
i've faced with problam that i don't know how to connect mini app to user's telegram_id. I'm new with this tecknologie, and dont know how to do this. I try to use django on this project and the problam is that i dont know how to safely transfer collected data from runbot.py to views.py.Could anybody help me? -
django flatpages will show only one page
I'm trying to use flatpages in my Django application. I installed it properly as far as I can see and created 2 pages. Using the shell, when I try: >>> from django.contrib.flatpages.models import FlatPage >>> FlatPage.objects.all() <QuerySet [<FlatPage: /pages/en-US/about/privacy/ -- Privacy Policy>, <FlatPage: /pages/fr-FR/about/privacy/ -- Politique de Confidentialité>]> I can see my 2 pages. But in a template, I'm using: {% get_flatpages as about_pages %} {% for page in about_pages %} <a class="navbar-item" href="{{ page.url }}">{{ page.title }}</a> {% endfor %} And there I can see only the last page. Also when I access directly the first page using it's full URL (http://127.0.0.1:8000/pages/fr-FR/about/privacy/) it displays nicely but when I try the same with the other one (http://127.0.0.1:8000/pages/en-US/about/privacy/) I get a 404. I tried to change the name of the first page, but nothing works. Any idea??? -
Naming an abstract model Django
What is the standard for naming Django abstract classes? My team leader insists that the name of the abstract model should consist of the fields available in it. for example, IsPublishedAndCreatedAt. But My class: class BaseContentProperties(models.Model): is_published = models.BooleanField() created_at = models.DateTimeField() class Meta: abstract = True class Category(BaseContentProperties): ... class Location(BaseContentProperties): ... class Post(BaseContentProperties): ... But if there are more fields, then the name will be more, for example, IsPublishedAndCreatedAtAndPublishedAt.... Who is right?) If there are some generally established recommendations on this issue, you can send a link so that you can familiarize yourself. Thanks I described my problem above -
Double model creation after payment in django website
I am currently working on Learning management course using Django and React .I am creating payment gateway using stripe . After the payment is successfully done , the courses should be called enrolled courses and a model of it created after payment . But for some issue , double course model gets created after payment for each course purchased. I don't know the issue in code. I have attached the code of payment and model created .enter image description here enter image description here enter image description here I tried to pay using stripe and get the enrolled course created of that course. But duplicate (double) enrolled course created for some reason. -
How to get fields names that were chosen with method "only()"?
For example, I have simple model: class Person(models.Model): id = models.BigAutoField("id", primary_key=True) first_name = models.CharField(max_length=150) surname = models.CharField(max_length=150) age = models.IntegerField() I use method only to choose fields I need: queryset = Person.objects.all().only("first_name", "age") How can I get fields names("first_name", "age") that were chosen? I tried this: queryset.query.get_loaded_field_names() But I got this error: AttributeError:'Query' object has no attribute 'get_loaded_field_names' -
js files in the admin
I load some js files in the admin using a custom admin site, let's call it custom_admin_site.html. In this template I override some blocks: {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrahead %} <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" /> <script src="{% static 'admin/src-min-noconflict/ace.js' %}" referrerpolicy="no-referrer"></script> <script src="{% static 'js/htmx.min-1.9.11.js' %}"></script> {% endblock %} When I use these libraries, on the main page (/admin) they work just fine. When I override other templates, for example I have: projectname \ templates \ admin \ appname \ modelname \ change_form.html: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} ... and I cannot access my libraries form here. Do I need to add something like this in my 'change_form.html`? {% block extrahead %} {{ block.super }} {% endblock %} or can I somehow make sure that other htmls also use my extended custom_admin_site.html and not the normal admin/base_site.html? Or am I approaching this the wrong way and should I define a Media subclass with the js files in the admin.py where it is needed? -
ModuleNotFoundError: No module named 'fullstackcap'
I am doing some cleaning up on a recent project and all of a sudden when running the project, the terminal spits out the error in the title. I was also trying to figure out and environment variable error as well. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fullstackcap.settings') application = get_wsgi_application() settings.py 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.1/howto/deployment/checklist/ ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'fullstackcapapi', ] # UPDATE THIS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'fullstackcap.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 = 'fullstackcap.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True … -
Execute callback when django.cache.set timeout is exceeded
I use Django cache with django-redis==5.0.0 like this: cache.set(f'clean_me_up_{id}', timeout=10) Storing an entry into cache, which will be cleared after timeout, works perfectly for me. What I´m trying to acheive, is to execute also some cleanup code (as a callback?) when the cache is deleted. Is there some easy way to do this as it would be extremely helpful. -
graphene-django get_node vs get_queryset
I'm currently getting acquainted with graphene-django and there's one aspect of it I'm not quite getting my head around. I would like to let my users use GraphQL to query our database. I would like them to be able to filter their results by attribute values, so I am providing my models as a ThingNode with filter_fields and interfaces = (relay.Node, ) rather than as a ThingType. Now, all examples I could find tell me to overload get_node() if I want to interact with the output, for instance in order to check for the user's permissions. However my implementation, as I have it working now, never gets past get_node(), but instead uses get_queryset(). I've looked into existing packages that offer permission management, such as django-graphene-permissions but this also hooks into get_node(). I am now unsure if I should just put my permission checks into ThingNode.get_queryset() instead, or is the fact that my code deviates from all the examples I find means that I'm setting this up the wrong way altogether. If anyone could give me some hints on this I'd be massively grateful! -
Error while installing scikit-learn with pip : Preparing metadata (pyproject.toml) did not run successfully
I try to install scikit-learn==1.2.2 for the django project and I got this error. Collecting scikit-learn==1.2.2 Using cached scikit-learn-1.2.2.tar.gz (7.3 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [36 lines of output] Partial import of sklearn during the build process. Traceback (most recent call last): File "D:\Group Project Backend\Prediction\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() File "D:\Group Project Backend\Prediction\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Group Project Backend\Prediction\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 149, in prepare_metadata_for_build_wheel return hook(metadata_directory, config_settings) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\build_meta.py", line 366, in prepare_metadata_for_build_wheel self.run_setup() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\build_meta.py", line 487, in run_setup super().run_setup(setup_script=setup_script) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 669, in <module> File "<string>", line 663, in setup_package File "<string>", line 597, in configure_extension_modules File "C:\Users\ASUS\AppData\Local\Temp\pip-install-xv622fd3\scikit-learn_6df30b226b524d1caf236a6b94005795\sklearn\_build_utils\__init__.py", line 47, in cythonize_extensions basic_check_build() File "C:\Users\ASUS\AppData\Local\Temp\pip-install-xv622fd3\scikit-learn_6df30b226b524d1caf236a6b94005795\sklearn\_build_utils\pre_build_helpers.py", line 82, in basic_check_build compile_test_program(code) File "C:\Users\ASUS\AppData\Local\Temp\pip-install-xv622fd3\scikit-learn_6df30b226b524d1caf236a6b94005795\sklearn\_build_utils\pre_build_helpers.py", line 38, in compile_test_program ccompiler.compile( File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 343, in compile self.initialize() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\msvc.py", line 230, in msvc14_get_vc_env return _msvc14_get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\msvc.py", line 187, in _msvc14_get_vc_env raise distutils.errors.DistutilsPlatformError("Unable to find … -
How to Filter by Status in Django Rest Framework with Square Brackets in Query Params
I'm encountering an issue with filtering a model by status in Django Rest Framework. Here's my current setup: When I filter using status=1,14, it works perfectly: class DepartmentFilter(filters.FilterSet): search = filters.CharFilter(method='filter_search') status = filters.CharFilter(method='filter_status') class Meta: model = Department fields = ['search', 'status'] def filter_search(self, queryset, name, value): print("filter_search", value) return queryset.filter(Q(token__icontains=value)) def filter_status(self, queryset, name, value): print("filter_status", value) # Verificar que el filtre s'executa if value: status_values = value.split(',') return queryset.filter(status__id__in=status_values) return queryset However, I'm having trouble capturing the query parameter when I use status[]=1,14. I've tried the following without success: status = filters.CharFilter(method='filter_status[]') status = filters.CharFilter(method='filter_status%5B%5D') There doesn't seem to be a way to create a function to capture this. Resolving status[] is a first step because ultimately, I want to work with the call filters[status][] = 1,14. I haven't found a way to handle this. Can anyone provide some guidance? Thank you! -
facing issues with python module installation
i am gettinig error as : ModuleNotFoundError: No module named 'currency_converter' i installed by command: pip3 install currency_converter after instaltion show succesfull, even showing madule as exit on checking by: pip3 show currency_converter after that use migration command then its show same error as abobe Migration: python3 manage.py makemigrations please help -
how to fix bad request error in platform.sh
im learning web deployment using platform.sh. i pushed my files to platform.sh by command "platform push" and then supposed to get my live url by commanding "platform url" i got some list of urls but in the browser it is showing error 502 "bad gateway" i tried every thing from checking internet connections, updating CLI,DNS etc. is there any command im missing or any pushing issues? help out guys. this is routes.yaml # Each route describes how an incoming URL will be processed by Platform.sh. "https://{default}/": type: upstream upstream: "ll_project:http" "https://www.{default}/": type: redirect to: "https://{default}/" expection! when i commanded "platform url" after "platform push", im supposed to get some list of urls and chose 1 out of them to be my web address according to the book "python crash course by erric maththes" latest edition page no 456. But i was promted 4 urls and no option to select. when i copied all the urls in my brave browser i got error 502 "bad request" in every site. -
venv\Scripts\python.exe - The FastCGI process exited unexpectedly
I'm currently working with Python 3.11.9 and Django 4.2.4 for my project. However, I've encountered an issue where the FastCGI process exits unexpectedly with the following error message: kttProject\venv\Scripts\python.exe - The FastCGI process exited unexpectedly. Despite attempting various troubleshooting steps, including checking permissions and seeking solutions from online resources, I haven't been able to resolve this error. Could someone please provide insights or suggestions on how to troubleshoot and resolve this issue effectively? Any assistance would be greatly appreciated.Thank you. -
Pip not installing any package
I have been trying to install django on my virtual environment using pip to learn creating websites, but whenever i try to install django using the command pip install django the terminal out put is the following: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadata (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")) The result is an OSError. however I thought it would be better to show all the output. I reinstalled python. I tried to install it out of a virtual environment. I tried to install it other packages to see if its django's fault. I tried running the … -
Django Manifest with Elastic Beanstalk Docker Platform
I have my application running on Elastic Beanstalk with Docker Platform and I am using my own nginx container. Recently for serving static files I used Manifest django tool which is successfully running but after deploying this tool I am getting this on my web I wanna tell you that the staticfiles.json is perfectly being created in my staticfiles folder and the new versions of my static files are perfectly being generated. Here is my settings.py And here is my urls.py I even tried not in if statement cuz my app holds DEBUG-False on elastic beanstalk. The logs are saying nothing - Please HELP!!! -
Trouble running django app in vs code on macos, I'm on the correct directory I believe
So I am trying to run my django project in my vs code terminal but I get the following error message below. I'm in the right directory, that is User/coreyvigil/remotifyIO. But I do run this command `python manage.py runserver'. PS I would like to add that I am currently using a virtual environment for Python .venv. I eve tried looking at my settings for Python. Anything would help me, here is my Git URL if you need it. https://github.com/remoteconn-7891 (.venv) coreyvigil@Coreys-Air remotifyIO % python manage.py runserver /Library/Frameworks/Python.framework/Versions/3.12/Resources/Python.app/Contents/MacOS/Python: can't open file '/Users/coreyvigil/remotifyIO/manage.py': [Errno 2] No such file or directory -
Issue with creating new pigeon and his parent records in a Django form
I am new to programming and currently learning Django. I am working on a web application where users can register new pigeons into a database. The registration form includes fields for the pigeon's name and a long dropdown menu with all the existing records for the father and the mother, which becomes quite tedious with many pigeons. Is there a strategy to solve this? Something like search fields to allow the user to search and select the father and the mother? And if parents do not exist, to add functionality to register them from there, similar to the admin form? If the father or mother doesn't exist in the database, the user should be able to create a new parent record directly from the main registration form without leaving the page. I have implemented the following model for the Pigeon: `python from django.db import models class Pigeon(models.Model): GENDER_CHOICES = ( ('male', 'Male'), ('female', 'Female'), ) name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) father = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children_set') mother = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children_set') def __str__(self): return self.name ` I'm facing an issue where I can't seem to create new parent records from the main registration form. Could … -
Getting ConnectionError while running elastic search using docker in django project
I am recently learning docker. I want to run elasticsearch using docker. It works fine when I only add code to run elastic search in docker file. But I am getting Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError when I update docker-compose.yml file to start server, postgresql db and elastic search. Below is the code for dockerfile and docker-compose.yml file. Dockerfile FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . /code/ docker-compose.yml `version: '3' services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: myproject POSTGRES_USER: myprojectuser POSTGRES_PASSWORD: password web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - es environment: - DATABASE_URL=postgres://myprojectuser:password@db:5432/myproject es: image: docker.elastic.co/elasticsearch/elasticsearch:7.14.0 environment: - discovery.type=single-node ports: - "9200:9200" volumes: - es_data:/usr/share/elasticsearch/data volumes: postgres_data: es_data: ` Can anyone help me to fix this error please? I tried to run only elastic search container, it works fine. But when I update docker-compose.yml file to start django server, pg db and elastic search I am getting issue. -
Python Admin Issue
This is my admin.py code; from django.contrib import admin from userauths.models import User class UserAdmin(admin.ModelAdmin): list_display=['username', 'email', 'bio'] admin.site.register(User, UserAdmin) I want my admin page to display a list of users in a table but unfortunately bringing the below error; File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/contrib/admin/checks.py", line 51, in check_admin_app errors.extend(site.check(app_configs)) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/contrib/admin/sites.py", line 96, in check if modeladmin.model._meta.app_config in app_configs: ^^^^^^^^^^^^^^^^ AttributeError: 'User' object has no attribute 'model' -
After pushing log out button the app is forwarding me to empty page
After pushing log out button the app is forwarding me to https://it-company-task-manager-uzrc.onrender.com/accounts/login/ But there is an empty page and after log out I'm still logged in and can do things (create task etc) I tried to solve it in different ways, but nothing changes. You can check it by yourself: https://it-company-task-manager-uzrc.onrender.com sidebar.html: <li class=""> <a href="{% url 'login' %}" class="icon"> <i class="fa-solid fa-right-from-bracket"></i> <span class="ml-4">Log out</span> </a> </li> login.html: {% extends "base.html" %} {% load static %} {% block login %} <section class="login-content"> <div class="container"> <div class="row align-items-center justify-content-center height-self-center"> <div class="col-lg-8"> <div class="card auth-card"> <div class="card-body p-0"> <div class="d-flex align-items-center auth-content"> <div class="col-lg-6 bg-primary content-left"> <div class="p-3"> <h2 class="mb-2 text-white">Sign In</h2> <p>Login to stay connected.</p> {% if form.non_field_errors %} {{ form.non_field_errors }} {% endif %} <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <div class="floating-label form-group"> {% if form.username.errors %} {{ form.username.errors }} {% endif %} <input class="floating-input form-control" type="text" name="username" placeholder="Username"> </div> </div> <div class="col-lg-12"> <div class="floating-label form-group"> {% if form.password.errors %} {{ form.password.errors }} {% endif %} <input class="floating-input form-control" type="password" name="password" placeholder="Password"> </div> </div> </div> <input type="hidden" name="next" value="{{next}}" /> <button type="submit" class="btn btn-white">Sign In</button> </form> </div> </div> <div class="col-lg-6 content-right"> … -
Resolving Celery Timeout Issues on Heroku: 504 Errors for Long-Running Asynchronous Tasks
I have a Django v5.0.6 application (Python v3.12) in which I integrated Celery v5.4 to run asynchronous tasks, such as generating images via the OpenAI API, which takes about 2 minutes. The entire setup is deployed on Heroku. Here is the content of my Procfile: web: gunicorn mngrs_backend.wsgi --timeout 600 worker: celery -A mngrs_backend worker -l info --time-limit=7200 However, after 30 seconds, I get the following error in the logs: I am looking to increase the delay to avoid a timeout. Here are the attempts I made without success: Added --timeout 600 in the gunicorn command in the Procfile Added --time-limit=7200 in the celery command in the Procfile Added a timeout to the API request: requests.post(url, json=payload, headers=headers, timeout=600) Modified the configuration in celery.py app = Celery("mngrs_backend") app.conf.update( task_soft_time_limit=60 * 10, task_time_limit=60 * 12, ) Added in the project settings: CELERY_BROKER_TRANSPORT_OPTIONS = { "visibility_timeout": 60 * 60 * 2, # 2 hours } Locally with Celery, I do not have any timeout issues. I contacted Heroku support, but they told me the problem is with my Celery configuration. Does anyone have a solution? -
How to output the name of the current tag to the template? (The one we are in)
I'm trying to display the name of the current tag, i.e. the one we are in. Does not work. How to write correctly to display a tag in a template? #Models from django.db import models from taggit.managers import TaggableManager class Blog(models.Model): title = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=550) tags = TaggableManager() def __str__(self): return self.title #Views from django.shortcuts import render from django.views.generic import ListView from .models import * from taggit.models import Tag class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class PostIndexView(TagMixin,ListView): model = Blog template_name = 'blog.html' queryset=Blog.objects.all() context_object_name = 'posts' class TagIndexView(TagMixin,ListView): model = Blog template_name = 'blog.html' context_object_name = 'posts' def get_queryset(self): return Blog.objects.filter(tags__slug=self.kwargs.get('tag_slug')) #Templates {% if tag %} <h3>Posts by tag: {{ tag }}</h3> <!-- Does not display tag name --> {% endif %} P.s. The site asks for more description, but what else can be described here? The problem with the output is described -
Django Best practices: migration & contenarization
I am working on a Django API and I'd like to add a bit of CI/CD to it. It dockerize my app with FROM python:3.12 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 ENV DJANGO_SETTINGS_MODULE=vocab_dictionnary.settings CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] I then add a docker-compose.yml services: db: image: postgres:14 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_USER=" - "POSTGRES_PASSWORD=" - "POSTGRES_DB=" ports: - 5438:5432 healthcheck: test: pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-${POSTGRES_USER:-postgres}} interval: 5s timeout: 5s retries: 120 start_period: 30s web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: db: condition: service_healthy environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: The end of my main.yml file for github actions looks like this - name: Run Database Migrations uses: appleboy/ssh-action@master with: host: ${{ secrets.SERVER_HOST }} username: ${{ secrets.SERVER_USERNAME }} password: ${{ secrets.SERVER_PASSWORD }} script: | cd /${{ secrets.SERVER_USERNAME }}/api/vocab_dictionnary/ docker compose exec web python manage.py migrate Finally, to simplify my local dev workflow, I added this in a Makefile: restart: docker compose down docker compose build docker compose up -d docker compose run web python3 manage.py makemigrations docker compose run web python3 manage.py migrate My first problem is that my migrations doen't apply …