Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Migration failed in Wagtail 5.0.1 on MSSQL
after install wagtail, i have some problems how to use mssql in wagtail cms? i have error when migration wagtail when use mssql, im use wagtail v5 and django v4.2.2 its error log django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The index 'content_object_idx' is dependent on column 'content_type_id'. (5074) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]ALTER TABLE ALTER COLUMN content_type_id failed because one or more objects access this column. (4922)") is it possible use mssql for wagtail cms database? how to Solve migration to MSSQL on wagtail cms ? -
deciding a sofware stack angular+django+vite? [closed]
I work for a firm that gave me the task to select a software stack that suits our needs i already have some idea of what it is going to be but i am the only technical people in the firm so i need advice. I just got out of school so its kinda overwelming. What we need -One MPA (so ssr and seo) -Two SPA on the same domain as the MPA -A backend that works with mssql and the frontend Because it is a pretty big enterprise project and my devs are in inda and familiar with angular i want to use angular with primeNG on top. For the backend i think django will be my choice becauce it works with our database and the build in functionalities seem very nice. I would also like to use vite for faster developing time but i am not sure if it will suit my needs. The main question is can i use angular for the MPA so ssr and angular for the SPA's on the same domain, it opens a new tab when a link is clicked to the SPA. I need to hydrate some parts of pages of the … -
Django: request.POST contains only the last form in my formset
When I run pprint(request.POST), it only returns the data of the last form of my formset. Why is this happening? Here is my code. My models.py: class Order(models.Model): date = models.DateField(unique=True, blank=True, null=True) first_course = models.CharField(null=True, blank=True, unique=False, max_length=30) first_course_quantity = models.IntegerField() second_course = models.CharField(null=True, blank=True, unique=False, max_length=30) second_course_quantity = models.IntegerField() dessert = models.CharField(null=True, blank=True, unique=False, max_length=30) dessert_quantity = models.IntegerField() drink = models.CharField(null=True, blank=True, unique=False, max_length=30) drink_quantity = models.IntegerField() def __str__(self): return f"Date of order: {self.date}" My forms.py: class DisabledOptionWidget(forms.Select): def render(self, name, value, attrs=None, renderer=None): html_code = super(DisabledOptionWidget, self).render(name, value, attrs, renderer) html_code = html_code.replace(f'<option value=""', f'<option value="" disabled') return html_code class OrderForm(forms.ModelForm): first_course = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("first_course", flat=True))], widget=DisabledOptionWidget, required=False) first_course_quantity = forms.IntegerField(min_value=0) second_course = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("second_course", flat=True))], widget=DisabledOptionWidget, required=False) second_course_quantity = forms.IntegerField(min_value=0) dessert = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("dessert", flat=True))], widget=DisabledOptionWidget, required=False) dessert_quantity = forms.IntegerField(min_value=0) drink = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("drink", flat=True))], widget=DisabledOptionWidget, required=False) drink_quantity = forms.IntegerField(min_value=0) date = forms.DateField(required=False) class Meta: model = Order fields = "__all__" def save(self, commit=True): if commit: … -
Django issue with validating data in form
So I've been working my way through this tutorial, and I've run into a problem I can't figure out. I'm hoping someone can show me the way. I have a new user registration form I'm working on, and I can't get the data to validate with form.is_valid(). In views.py, the if form.is_valid() is supposed to validate the data inputted into the form, but instead it returns "Invalid" no matter what. I'm relatively new to Python and Django, so any assistance would be appreciated. views.py: # main/views.py from django.http import HttpResponse from django.contrib.auth import 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': return render( request, 'users/register.html', {'form': CustomUserCreationForm} ) elif request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return HttpResponse('<h1>Validated!</h1>') # return render(redirect(reverse('dashboard'))) else: return HttpResponse('<h1>Invalid</h1>') forms.py: # main/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ('email',) register.html: <!-- main/templates/users/register.html --> {% extends 'main.html' %} {% block content %} …