Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django migrations error. I migrated model but changes not aplied
i added new field to model and deleted another field but not deleting old field and not adding new feld.I deleted all migration files and re migrate it problem is same not working migration. It was a message " No migrations to apply. here is result after migrate app here is my changed model -
how to update default status of any record using django rest framework
I have three buttons named start, stop and cancel in my project. There is a status field which is default registered. When the 'start' button is clicked, the status should update 'running'. When the 'close' button is clicked, the status should update 'closed'. When the 'cancel' button is clicked, the status should update 'cancelled'. @csrf_exempt def projectApi(request,id=0): if request.method=='GET': project = Project.objects.all() project_serializer = ProjectSerializer(project, many=True) return JsonResponse(project_serializer.data, safe=False) elif request.method=='POST': project_data = JSONParser().parse(request) project_serializer = ProjectSerializer(data=project_data) if project_serializer.is_valid(): project_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed to Add",safe=False) This is my views.py file. -
Customizing Django viewflow url
I am using the django-viewflow application with a custom view representing a stock item record where there are a number of workflows that can be attached to the record (registering/ issuing/ disposing etc.). In the detail view of the record I want to have a list of all workflows attached to the item and to be able to list all the tasks related to that workflow. I am aiming for a url that looks like .../asset/3/ - for the detail view .../asset/3/register/93/ - for the register process (and subsequent tasks) .../asset/3/movement/1/ - for movement process (and subsequent tasks) etc My application url.py looks like: asset_urls = FlowViewSet(AssetFlow).urls movement_urls = FlowViewSet(MovementFlow).urls app_name = 'asset' workflowurlpatterns = [ # path('ajax/load-budget_lines/', views.load_budget_lines, name='ajax_load_budget_lines'), path('viewflow/', include((asset_urls, 'asset'))), path('movement/', include((movement_urls, 'movement'))), # path('', views.Detail.as_view(), name='detail'), ] urlpatterns = [ path('', views.List.as_view(), name='assets'), path('<int:asset_pk>/', views.Detail.as_view(), name='detail'), path('<int:asset_pk>/', include((workflowurlpatterns))) ] The issue is that all the urls generated by the template tag {% flowurl task user=request.user as task_url %} fail with a NoReverseMatch error. Is there a clever way to pass the asset_id so that the urls work (or another solution)? -
unsupported format character '_' (0x5f)
models.py class ChangingDocument(PrivateCommentMixin, models.Model): # Список изменяющих документов. treaty = models.ForeignKey("treaties.Treaty", on_delete=models.CASCADE, blank=False, null=False, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) changing_document = models.ForeignKey("treaties.Treaty", on_delete=models.CASCADE, blank=False, null=False, related_name="%(app_label)s_%(class)_changing_documents_related", related_query_name="%(app_label)s_%(class)ss_changing_documents", ) def __str__(self): return str(self.changing_document) Stack trace (venv) michael@michael:/media/michael/750/Programming/treaty_outer/treaty_project$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/media/michael/750/Programming/treaty_outer/treaty_project/changing_documents/models.py", line 6, in <module> class ChangingDocument(PrivateCommentMixin, File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/base.py", line 194, in __new__ new_class.add_to_class(obj_name, obj) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/fields/related.py", line 866, in contribute_to_class super().contribute_to_class(cls, name, private_only=private_only, **kwargs) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/fields/related.py", line 357, in contribute_to_class related_name %= { ValueError: unsupported format character '_' (0x5f) at index 22 Problem I have … -
How upload Django web application using React JS?
Anybody knows how should I upload my Django web application using font-end React JS on Cpanel? -
Not able to override unittest `startTest` and `stopTest` isn’t working correctly in custom test runner when using with –parallel
I have override startTest and stopTest from unittest TextTestResult class and used it in my custom test runner. It’s working correctly in normal scenario but not working correctly when using with --parallel flag. I tried to debug and found the time elapsed b/w startTest and stopTest is coming very very small. Like 4.8000000000492093e-05 which is incorrect. Would someone please tell me is it the right hooks for --parallel flag or I have to use some another hook? -
Reorder models in admin
Could you tell me how to organise an arbitrary order in the admin site> Maybe something ready to use from here https://djangopackages.org/grids/g/admin-interface/ There exists django-modeladmin-reorder But it's a long time since it has been updated. Could you recommend something to me instead of that? -
Pk becoming lost from django url
I have a view defined as follows: u = reverse("ipsych_results", kwargs = {"ipsychcase_id": ipsychvisit_instance.ipsychvisit_id}) print(f'the url being passed to redirect is {u}') return redirect(u) It prints out: the url being passed to redirect is /ipsych/processed/8b429f6d-8538-4af6-90b9-102168887e34/ When I enter http://localhost:8000/ipsych/processed/8b429f6d-8538-4af6-90b9-102168887e34/ into the browser, the subsequent view is generated correctly. However, when I click the Submit button that triggers POST (which prints out the above), I get the following error: Page not found (404) "/Users/a/Documents/websites/website/ipsych/processed" does not exist Request Method: GET Request URL: http://localhost:8000/ipsych/processed// Raised by: django.views.static.serve Why is the ipsychcase_id getting lost? -
How to call an API function using a view
I am trying to fetch data from an API and render that data using a view. I am not sure what is wrong. Could someone please show me what I need to change in order to make it work ? My fixtures.py: def get_fixtures(): credentials = service_account.Credentials.from_service_account_file( settings.GOOGLE_CALENDAR_CREDENTIALS_FILE, scopes=['https://www.googleapis.com/auth/calendar.readonly'] ) service = build('calendar', 'v3', credentials=credentials) events = service.events().list(calendarId='u6kmbrsrt5qr3r6gjrtsussomc@group.calendar.google.com').execute() fixtures = [] for event in events['items']: fixture = { 'summary': event['summary'], 'start': event['start'].get('dateTime', event['start'].get('date')), 'end': event['end'].get('dateTime', event['end'].get('date')), } fixtures.append(fixture) My views.py : def fixtures_view(request): fixtures = get_fixtures() return render(request, 'fixtures.html', {'fixtures': fixtures}) print(fixtures) There's nothing on my HTML page and nothing is being printed on the command prompt either. -
Static files not loading on Django deploy on digitalocean app
I am trying to deploy a Django application on DigitalOcean. However, static files are not getting served on the server. I am not sure what the issue is since they work fine locally. The following is my settings file: from django.core.management.utils import get_random_secret_key from pathlib import Path import os import sys import dj_database_url BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) DEBUG = os.getenv("DEBUG", "False") == "True" DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",") INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', "whitenoise.runserver_nostatic", # new "django.contrib.staticfiles", ] 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 = 'myapp.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 = 'myapp.wsgi.application' if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ … -
django subdomains error namespace does not exist
Trying to configure subdomains. ie. two.example.com default domain www.example.com but getting error "app_two is not a registered namespace" via {% url 'app_two:app-two-list' %} in base.html I've also tried {% host_url 'app-two-list' host 'two' %} but it redirects to just two and not two.example.com project urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("app_one.urls", namespace="app_one")), ] app_one urls.py app_name = "app_one" urlpatterns = [ path("", views.home, name="home") ] app_two urls.py app_name = "app_two" urlpatterns = [ path("", AppTwoListView.as_view(), name="app-two-list"), path("new/", AppTwoCreateView.as_view(), name="app-two-create") ] project hosts.py host_patterns = [ host("www", settings.ROOT_URLCONF, name="www"), host( "two", include("app_two.urls", namespace="app_two"), name="two" ), ] project setting.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "django.contrib.redirects", "django_hosts", "app_one", "app_two", ] MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", ... "django_hosts.middleware.HostsResponseMiddleware", ] ROOT_URLCONF = "project.urls" ROOT_HOSTCONF = "project.hosts" DEFAULT_HOST = "www" SITE_ID = 1 projects base.html {% load static %} {% load hosts %} <nav> <a class="navbar-brand" href="{% url 'app_one:home' %}"> <img src="{% static 'app_one/svg/logo.svg' %}" alt="App One Logo" height="30"> </a> <a class="nav-link" style="color:#ffff" href="{% url 'app_two:app-two-list' %}">two</a> </nav> -
How do I run "python manage.py migrate" in a Visual Studio Django Web Project?
I am trying to run the default Django Web Project using Visual Studio 2022. I have reached this point: I open a Developer PowerShell window and run "python manage.py migrate". However, this fails because manage.py is in a sub-directory. So I run "python DjangoWebProject\manage.py migrate". This fails with "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" What should I do to get this working? -
Why do multiple test files cause Django issues when running in parallel?
I am using django 4.1 on windows. running my tests sequentially (python manage.py test) works fine. but when I run my tests in parallel (python manage.py test --parallel) I get the following error File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\multiprocessing\process.py", line 315, in _bootstrap self.run() File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\multiprocessing\process.py", line 108, in run self._target(*self._args, **self._kwargs) File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\multiprocessing\pool.py", line 109, in worker initializer(*initargs) File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\site-packages\django\test\runner.py", line 420, in _init_worker process_setup(*process_setup_args) TypeError: process_setup() missing 1 required positional argument: 'self' I created a project and made a folder underneath the main app folder for my tests called "tests" next to manage.py I have two test files test_losing_hair.py: from django.test import TestCase class WhyTest(TestCase): def test_counting_scheme(self): self.assertTrue(True) and test_rapidly.py: from django.test import TestCase class WontThisWorkTest(TestCase): def test_counting_scheme(self): self.assertTrue(True) What Am I doing wrong here? I've noticed running it in parallel works if I choose one file or the other, but both at the same time creates the error above. -
How to translate the url in Django Admin?
I'm trying to translate the entire Django Admin including the url from English to French. This is my django-project below. *I use Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-apps.py |-my_app2 └-locale └-fr └-LC_MESSAGES |-django.po └-django.mo And, this is core/settings.py below: # "core/settings.py" MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) And, this is core/urls.py below: # "core/urls.py" from django.contrib import admin from django.urls import path from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( path('admin/', admin.site.urls) ) And, this is my_app1/models.py below: # "my_app1/models.py" from django.db import models from django.utils.translation import gettext_lazy as _ class Person(models.Model): name = models.CharField(max_length=20, verbose_name=_("name")) class Meta: verbose_name = _('person') verbose_name_plural = _('persons') And, this is my_app1/apps.py below: # "my_app1/apps.py" from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class MyApp1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_app1' verbose_name = _('my_app1') And, this is locale/fr/LC_MESSAGES/django.po below: # "locale/fr/LC_MESSAGES/django.po" ... #: .\core\settings.py:140 msgid "English" msgstr "Anglais" #: .\core\settings.py:141 msgid "French" msgstr "Français" ... #: .\my_app1\apps.py:7 msgid "my_app1" msgstr "mon_app1" #: .\my_app1\models.py:6 msgid "name" … -
I'd like to convert a little code from Flask for use in Django
In Flask I have a simple combobox and when I select an item, it is printed in the textbox (using simple conditions). All very simple. I'm new to Django and learning, so I'm having a hard time using this Flask code in Django, because I don't know where and how to use it. Of course the language is the same, but I change the frameworks. I'll show you the code I use in both Flask and Django. In Django I pasted the def dropdown function into app1/views.py. I created app1/forms.py page where there is combobox and textbox. In index.html I don't know how to set the code. I don't know if I did these things correctly. Can you help me please? Thank you Here is the code I use in Flask: Flask: app.py colours = ["Red", "Blue", "Black", "Orange"] @app.route('/') def index(): return render_template("index.html", colours=colours, chosen="Black") @app.route("/combobox", methods=["GET","POST"]) def dropdown(): picked = request.form['colours'] if picked == 'Red': message = "<<< You chose red" elif picked == 'Blue': message = "<<< You chose blue" elif picked == 'Black': message = "<<< You chose black" else: message = "<<< Oh no, you chose orange" return render_template("index.html", colours=colours, chosen=picked, message=message) Flask: index.html <form … -
When I wanna dockerize, I get: django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")
I am attempting to dockerize a Django project that features a MySQL database and nginx. When I run the docker-compose up --build command, I receive the error message django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)"). Here's my docker-compose.yml file: version: '3.7' services: app: build: ./app env_file: - .env container_name: app restart: always expose: - 8000 command: bash -c "python3 manage.py collectstatic --noinput && python3 manage.py migrate --noinput --fake-initial && \ gunicorn -b 0.0.0.0:8000 veblog.wsgi" environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_HOST=sqldb mem_limit: 1g depends_on: - sqldb # - nginx volumes: - ./volumes/app:/app - type: bind source: ./volumes/media target: /app/media - type: bind source: ./volumes/static target: /app/static nginx: build: ./nginx container_name: nginx restart: always ports: - 8000:80 sqldb: image: mysql:latest container_name: sqldb restart: always depends_on: - nginx expose: - 3306 environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD} - MYSQL_INITDB_SKIP_TZINFO=true - MYSQL_INIT_COMMAND=SET GLOBAL host_cache_size=0; volumes: - type: bind source: ./volumes/dbdata target: /var/lib/mysql - /usr/share/zoneinfo:/usr/share/zoneinfo:ro This is my Dockerfile in the app directory: FROM python:3 ENV PYTHONDONTWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /app WORKDIR /app COPY . . RUN apt update RUN apt install gcc python3-dev musl-dev -y RUN pip install --upgrade pip … -
Django Foreignkey or onetoone models create,edit,view within an Modelform
Hy all, I am building an HR management system, i have below models class EmployeeDetails(models.Model): EMP_NO = models.CharField(max_length=6,primary_key=True,validators=[Validation]) EMP_First_Name = models.CharField(max_length=50,null=False,blank=False,validators=[Validation]) passport = models.OneToOneField('PassportDetails',on_delete=models.CASCADE,related_name='employee_passport',null=False,blank=False) visa = models.ForeignKey(Visa_Details,on_delete=models.CASCADE,null=False,blank=False) class PassportDetails(models.Model): Passport_No =models.CharField(max_length=20,null=False,primary_key=True,validators=[Passport_Validation]) class Visa_Details(models.Model): VISA_NO=models.CharField(max_length=19,null=False,primary_key=True,validators=[Visa_Validators])# in admin panel we can see below buttons and features enter image description here i want same feature for my below custom buttons enter image description here i tried using inline-forms, calling models normal way but it requires URL/int:passport_id/ but when rendering it wont load it because when creating a new employee details their wont be any id, i hope iam clear. <th>Passport No:</th> <td> {{ form.passport }} </td> <div class="Add" > <a href="#" data-tip="Add Passport" onclick="PassportAction('ADD')" id="AddClick"> <box-icon name='plus-medical' color="green" size="xs"> </box-icon> </a> </div> <div class="Edit"> <a href="#" data-tip="Edit Passport" onclick="PassportAction('EDIT')" id="EditClick"> <box-icon name='edit-alt' color="green" size="xs" class="Ico"> </box-icon> </a> </div> <div class="Show"> <a href="#" data-tip="Show Passport" onclick="PassportAction('VIEW')" id="ViewClick"> <box-icon name='expand-vertical' color="green" size="xs" class="Ico"> </box-icon> </a> </div> <script> function PassportAction(action){ var selectedPassport = document.getElementById('id_passport').value; var linkElement=null; var newHref=''; if(action=='ADD'){ linkElement=document.getElementById('AddClick'); newHref="{% url 'AddPassport' %}" } else if(action=='EDIT'){ linkElement=document.getElementById('EditClick'); newHref="{% url 'EditPassport' %}?passport_id=" + selectedPassport; }else if(action=='VIEW'){ linkElement=document.getElementById('ViewClick'); newHref="{% url 'ViewPassport' %}?passport_id=" + selectedPassport; } linkElement.href = newHref; alert(selectedPassport); } </script> My Main Goal: I want to … -
Connection Django + Celery + RabbitMQ with Docker
Im having some issues to run celery tasks in my django project, I am currently using rabbitmq as the broker. When I run the "docker compose up" and everything is on, if I run "celery status" inside the django container it fails with "kombu.exceptions.OperationalError: [Errno 111] Connection refused", but if I run it on my machine it works giving me the worker, how can I fix this? Here is my docker compose: version: "3" services: db: image: postgres networks: - django volumes: - postgres_db:/var/lib/postgresql/data ports: - 5432:5432 environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres rabbitmq: image: rabbitmq:3-management-alpine networks: - django volumes: - rabbitmq_data:/var/lib/rabbitmq/ - rabbitmq_log:/var/log/rabbitmq ports: - 5672:5672 - 15672:15672 celery_worker: build: context: . dockerfile: worker.dockerfile command: celery -A loan_manager worker --loglevel=info networks: - django environment: - CELERY_BROKER_TRANSPORT_URL=amqp://guest:guest@rabbitmq:5672// - DATABASE_NAME=postgres - DATABASE_USER=postgres - DATABASE_PASSWORD=postgres - DATABASE_HOST=db depends_on: - rabbitmq django_app: build: . command: > sh -c "python3 manage.py makemigrations --noinput && python3 manage.py migrate --noinput && python3 manage.py shell < ./utils/create_superuser.py && python3 manage.py runserver 0.0.0.0:8000" networks: - django ports: - "8000:8000" environment: - CELERY_BROKER_TRANSPORT_URL=amqp://guest:guest@rabbitmq:5672// - DATABASE_NAME=postgres - DATABASE_USER=postgres - DATABASE_PASSWORD=postgres - DATABASE_HOST=db depends_on: - db - rabbitmq volumes: postgres_db: rabbitmq_data: rabbitmq_log: networks: django: Here are the docker files for … -
I cannot run python manage.py in VS code after changing my computer username
When I run python manage.py runserver in vs code. I get the message below. "No Python at 'C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe'". I remembered changing my window username, I don't know if that is the cause. Could you give me an idea on how to fix this problem. Thank. -
Django get records using OuteRef filtering by max value
I have a Django model called CGDSStudy with fields name, url, and version: class CGDSStudy(models.Model): name = models.CharField(max_length=300) url = models.CharField(max_length=300) version = models.PositiveSmallIntegerField(default=1) Multiple versions of the same study can exist with the same URL, but I only want to retrieve studies of the last version. Here are three failed attempts: Attempt 1: from django.db.models import Max, OuterRef, Exists cgds_studies = CGDSStudy.objects.all() cgds_studies = cgds_studies.filter( Exists(CGDSStudy.objects.annotate(max_version=Max('version')).filter(url=OuterRef('url'), max_version=OuterRef('version'))) ) This attempt retrieves all studies instead of the studies from the last version. Attempt 2: cgds_studies = cgds_studies.filter( version=Max(CGDSStudy.objects.filter(url=OuterRef('url')).values('version')) ) This attempt raises the error "cgdsstudy.version" must appear in the GROUP BY clause or be used in an aggregate function. Attempt 3: cgds_studies = cgds_studies.filter( version=CGDSStudy.objects.filter(url=OuterRef('url')).annotate(max_version=Max('version')).values('max_version')[0] ) This attempt raises the error This queryset contains a reference to an outer query and may only be used in a subquery.. -
Django won't add the default language prefix in URL at startup
This is my first question here after 3 years of programming with Django, during which i always did all i could to solve problems by doing research. This time i'm really stuck... My issue is with a recent Django website ( url: h t t p s : // bucegipark. ro ) that should automatically add the language prefix when you access it (like for example going to this link), but it suddenly STOPPED doing that around a month ago and really cannot find the issue. I reset all language internalization settings twice. I should mention that with debug set to True it redirects to url with language prefix just fine, the issue comes up in production. When no prefix is shown after the url, database info is not either loaded. After starting the website, if i choose a language using the dropdown list i built, it redirects to that url with chosen language prefix. It does the same when i click the brand logo which has the {% url 'home' %} url attached to it and redirects to the homepage with the language prefix just fine. So theoretically, the urls.py code works fine i guess, the problem lies in … -
Trying to make an icon work while modifying a django template
How can make this icon show in my modified django template: I tried using font awesome link but it did not work the template was downloaded online and i am currently modfying it hence me encountering this issue. i triend downloading other fonts online but then none is the same as this -
Cannot translate only a model label in Django Admin
I'm trying to translate the entire Django Admin from English to French. This is my django-project below. *I use Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-apps.py |-my_app2 └-locale └-fr └-LC_MESSAGES |-django.po └-django.mo And, this is core/settings.py below: # "core/settings.py" MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) And, this is core/urls.py below: # "core/urls.py" from django.contrib import admin from django.urls import path from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( path('admin/', admin.site.urls) ) And, this is my_app1/models.py below: # "my_app1/models.py" from django.db import models from django.utils.translation import gettext_lazy as _ class Person(models.Model): name = models.CharField(max_length=20, verbose_name=_("name")) class Meta: verbose_name = _('person') verbose_name_plural = _('persons') And, this is my_app1/apps.py below: # "my_app1/apps.py" from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class MyApp1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_app1' verbose_name = _('my_app1') And, this is locale/fr/LC_MESSAGES/django.po below: # "locale/fr/LC_MESSAGES/django.po" ... #: .\core\settings.py:140 msgid "English" msgstr "Anglais" #: .\core\settings.py:141 msgid "French" msgstr "Français" ... #: .\my_app1\apps.py:7 msgid "my_app1" msgstr "mon_app1" #: .\my_app1\models.py:6 msgid "name" msgstr "nom" #: … -
how can I create an E-commerce CART system using python Django
I am developing an E-commerce website and encountering difficulties in implementing a cart system. please, Can anyone guide me through the process of implementing a cart system or provide some helpful resources? Thank you. -
python/django - convert 2 unequal querysets into "context" dictionary for passing on to template rendering in detail view
new to python/django framework. have got 2 querysets ('a' and 'b') using ldid=3 a=Ld.objects.filter(id=ldid).values() b=Ld.objects.get(id=ldid).ldref.all().values() Result: type of a and b is <class 'django.db.models.query.QuerySet'> a is <QuerySet [{'id': 3, 'docref': '228689', 'deno': 'ESGF387054', 'dedt': '20200905', 'bjno': 'ESGF387054', 'bjdt': '20200905', 'ccode_id': 3, 'gcode_id': 6, 'smcd_id': 3, 'cmcd_id': 1, 'schmcd_id': 6, 'invno': '2015407629', 'invdt': '20200905', 'item': 'MOBILE', 'brnd': 'VIVO', 'pref1': 'X50 KC472228', 'pref2': '', 'invamt': '34990', 'intper': '0', 'intamt': '0', 'emitot': '18', 'emiamt': '1944', 'emiano': '6', 'emiaamt': '11664', 'lnamt': '23327', 'lnbal': '23328', 'ddt': '20201010', 'cldt': '', 'szdt': '', 'szrem': '', 'lstatus': '', 'ndeno': '462DDFGF387054', 'ntdue': '23328', 'ntrcpt': '21384', 'nbal': '1944'}]> b is <QuerySet [{'id': 3, 'rtref': '2196146', 'ldref_id': 3, 'rtno': 'E504744', 'rtdt': '20210605', 'emi': '1944', 'pen': '0', 'remlt': 'false'}, {'id': 4, 'rtref': '2196147', 'ldref_id': 3, 'rtno': 'E504745', 'rtdt': '20210605', 'emi': '1333', 'pen': '0', 'remlt': 'false'}, {'id': 5, 'rtref': '2196148', 'ldref_id': 3, 'rtno': 'E504746', 'rtdt': '20210605', 'emi': '1545', 'pen': '0', 'remlt': 'false'}]> need to convert them to single dictionary, introducing a new key 1,2,3,4 etc. and values the dictionaries from the queryset. something like `context = { 1 : {'id': 3, 'docref': '228689', etc.,}, --> from a 2 : {{'id': 3, 'rtref': '2196146', 'ldref_id': 3, 'rtno': 'E504744', etc.,}, ` for use as context …