Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to efficiently integrate Django and Azure with a Machine Learning pipeline for data analysis?
What is Django? What is the Python libraries & dependencies of Django? How Django can be use to deploy machine learning models into cloud? I'm trying to get the answers accurately and resolve my doubts. I'm currently working on a data analysis project using Django for web development and I'm struggling to efficiently integrate Django's and Azure with my machine learning pipeline. Specifically, I'm facing challenges in seamlessly connecting my Django models to the data preprocessing, feature engineering, and model training steps of the machine learning workflow. -
Django Admin: Filtering Products Based on Parent and Child Collections
I'm using a self-referential relationship in my Django Collection model, and I want to modify the admin to filter products based on the collection. Currently, when the client filters products by a specific collection, it only shows products directly associated with that collection and not its child collections. I've modified the get_search_results function in the admin, but the generated query seems to append my filter with an AND condition instead of using OR. `Here's the current implementation of the get_search_results function: def get_search_results(self, request, queryset, search_term): collection_filter = request.GET.get('collection__id__exact') if collection_filter: try: collection_id = int(collection_filter) collection_q = Q(collection_id=collection_id) | Q(collection__parent_id=collection_id) queryset = queryset.filter(collection_q) print(queryset.query) except ValueError: pass print(queryset.query) return queryset, False enter code her` print result : SELECT "shop_product"."id", "shop_product"."created_at", "shop_product"."updated_at", "shop_product"."deleted_at", "shop_product"."unit_price", "shop_product"."inventory", "shop_product"."min_inventory", "shop_product"."collection_id", "shop_product"."promotions_id", "shop_product"."discount_id", "shop_collection"."id", "shop_collection"."created_at", "shop_collection"."updated_at", "shop_collection"."deleted_at", "shop_collection"."parent_id" FROM "shop_product" INNER JOIN "shop_collection" ON ("shop_product"."collection_id" = "shop_collection"."id") LEFT OUTER JOIN "shop_product_translation" ON ("shop_product"."id" = "shop_product_translation"."master_id") WHERE ("shop_product"."collection_id" = 2 AND ("shop_product"."collection_id" = 2 OR "shop_collection"."parent_id" = 2)) ORDER BY "shop_product_translation"."title" ASC, "shop_product"."id" DESC The resulting query appears to use AND conditions, which might be the reason for not including child collection products. How can I modify this to use OR conditions instead and ensure that … -
Reason: CORS header ‘Access-Control-Allow-Origin’ missing Error in django
I was struggling with CORS lately in my django project. I followed all needed steps like installing django-cors-headers and here is my settings.py: INSTALLED_APPS = [ 'rest_framework', # dasti ezafe shod 'rest_framework_simplejwt', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'carat', # dasti ezafe shod 'data', 'price', 'users', 'marketplace' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ORIGIN_WHITELIST = ( 'https://example.com', 'https://web.example.com', ) We build flutter web app and deployed in web.mydomain.com. from the beginning I faced with CORS errors but once I input those settings they all disappeared except one error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/media/images/image0_WEEP09I.png. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. I see this error in console tab of the inspector in firefox. Here is a part of my server response: HTTP/2 200 OK Content-Type: application/json Vary: Accept, origin,Accept-Encoding Allow: GET, HEAD, OPTIONS X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Access-Control-Allow-Origin: https://web.example.com Access-Control-Allow-Credentials: true Content-Length: 1884 Date: Sat, 03 Feb 2024 22:01:07 GMT Alt-Svc: h3=":443"; ma=2592000, h3-29=":443"; ma=2592000, h3-Q050=":443"; ma=2592000, h3-Q046=":443"; ma=2592000, h3-Q043=":443"; ma=2592000, quic=":443"; ma=2592000; v="43,46 ` I am really confused, anyone can guide me how to fix it? I added … -
Subprocess readline gets stuck
I am trying to build a terminal that works based on user input. I managed to get the output but readline() hangs after the output is generated. Is there anyway to stop readline after the user command executes. I have added a small example function to demonstrate the issue: def communicate_with_subprocess(process, command): try: # Send the command to the subprocess process.stdin.write(command + '\n') process.stdin.flush() lines = [] # Read the output from the subprocess for _line in iter(process.stdout.readline, b''): if _line == '': break lines.append(_line) return lines except Exception as e: print(f"Error executing command '{command}': {e}") return None # Example usage: subprocess_instance = subprocess.Popen(["/bin/bash"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) try: while True: user_input = input("Enter a command (type 'exit' to quit): ") if user_input.lower() == 'exit': print("Exiting...") break output = communicate_with_subprocess(subprocess_instance, user_input) print("Output:", output) finally: subprocess_instance.terminate() subprocess_instance.wait() The goal is to integrate it into a Django web application so if there any alternative solution that doesn't involve subprocess, that works too. -
Best solution for a limited number of dynamic model fields in Django app
I'm using Django to build an app for outdoor professionals (educators, guides) to keep track of their experience. Basically a logbook but eventually with features like collaboration, mapping, and reporting. You can see what I have so far here Currently working on the Experience model. An Experience will have standard attributes like where did you go, when, was it a professional trip or your own personal recreation, who were your clients? But it should also have attributes specific to each outdoor pursuit. For paddling, canoes, kayaks, etc. For whitewater, what grade (1, 2, 3..)? For climbing, what grade (5.10, 5.11..) and how many pitches? I'll build in many of these attributes, but I also want the app to be flexible enough that users can add their own sport (e.g., barefoot snow skiing) and create fields based on what an employer would need to know about their experiences in that sport. Many of the posts on dynamic model fields in Django are several years old. For example, this mentions EAV but says there's no clear leader for an implementation. Today Django EAV 2 seems to be pretty strong? Apparently there are still efficiency concerns compared to JSON? Given that most of … -
How to display dates?
I would like to use a loop to create columns and display forward dates in them. The code below displays everything correctly in the console, but I don't know how to display it to the user. list=[1,2,3,4,5,6] for l in list: date = datetime.date.today() next_date=date+timedelta(days=l) print(next_date) {% for l in l %} <p>{{ l }} - {{next_date}}</p> {% endfor %} Displays six numbered rows but each has the same date, and I would like to do from today's date to the date in 6 days. I tried this method but I get an error: 'datetime.date' object is not iterable' {% for l in next_data %} <p>{{ l }} </p> {% endfor %} -
Appending object To StructBlock inside StreamField Wagtail
trying to create new task dynamically in my project on wagtail using StreamField and StructBlock but without success. Please help me, I'm losing my mind over this. The user sets some parameters in the template and then supposed to create a new task... I tried three different options but this came out. I have with and without json.dumps and converting it into a StreamField or StructBlock Really losing my mind😀 this is my code: models.py: tasks = StreamField([ ("task", blocks.StructBlock([ ("name", blocks.CharBlock(required=True, max_length=150)), ("description", blocks.RichTextBlock(required=False)), ("image", ImageChooserBlock(required=False)), ("subtasks", blocks.ListBlock(blocks.StructBlock([ ("name", blocks.CharBlock(required=True, max_length=150)), ("description", blocks.RichTextBlock(required=False)), ]))) ])) ],null=True,blank=True,use_json_field=True) views: def create_task(request, project_id): # create a new task project = Project.objects.get(pk=project_id) # new_task = { # "name": request.POST["task_name"], # "description": str(request.POST["task_description"]), # "image": None, # "subtasks": [], # } # project.tasks.append(json.dumps(new_task)) # \Lib\site-packages\wagtail\blocks\stream_block.py", line 610, in _construct_stream_child # type_name, value = item # ^^^^^^^^^^^^^^^^ # ValueError: too many values to unpack (expected 2) # new_task = ('task',{ # "name": request.POST["task_name"], # "description": str(request.POST["task_description"]), # "image": None, # "subtasks": [], # }) # project.tasks.append(json.dumps(new_task)) # \Lib\site-packages\wagtail\blocks\stream_block.py", line 610, in _construct_stream_child # type_name, value = item # ^^^^^^^^^^^^^^^^ # ValueError: too many values to unpack (expected 2) new_task = { 'type': 'task', 'value': { … -
ModuleNotFoundError: No module named 'xppSite' when gunicorn and application are configured in different locations
I am getting this error and suspect failure could be due to my folder structure. That means virtual env folder is at: WorkingDirectory=/home/xxxx/xxagent ExecStart=/home/xxxx/xxagent/virtualenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ xppSite.wsgi:application and application files are at different location: /home/xxxx/xxagent/workspace/deploy/xppSite/wsgi.py In such situation, how do I fix this error: Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: File "<frozen importlib._bootstrap>", line 1176, in _find_and_load Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: ModuleNotFoundError: No module named 'xppSite' Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: [2024-02-03 05:52:30 +0000] [99254] [INFO] Worker exiting (pid: 99254) Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Worker (pid:99253) exited with code 3 Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Worker (pid:99254) was sent SIGTERM! Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Shutting down: Master Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Reason: Worker failed to boot. Feb 03 05:52:30 ubuntu-sfo3-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Feb 03 05:52:30 ubuntu-sfo3-01 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Thanks in advancestrong text -
SSL Certificate with Squarespace as DNS, Heroku as server, and QuotaGuard Static as static IP address provider: CN and Hostname mismatch
Squarespace is saying my SSL certificate is unavailable and Google Search also returns http instead of https, even though my site is able to use https and is flagged as secure by every browser I've tested: https://www.bencritt.net This is definitely related to how my website hosting is set up. My website is hosted on Heroku because it's a Django site and Squareqpace doesn't support hosting for sites developed with that framework. Heroku, unfortunately, uses dynamic IP addresses. So, my server's IP address is constantly changing. This makes setting up A records difficult. I have to run a third party service called QuotaGuard Static on my Heroku server that provides me with two static IP addresses. I use these two IP addresses for my A records in my DNS settings in Squarespace. At some point in the daisy-chain, the SSL is getting obscured and making Squarespace and Google both think I don't have it. Do you know how I can get both Squarespace and Google Search to recognize my website's SSL? I've tried adding schema to my website's code that specifies https in an attempt to force Google Search to return the https version of my site in Search results. I've … -
Django return render to datatable from edit view (or refhesh page to show uptated datatable)
I have a template that shows me a datatable, for each record a button that edits/delete the record through a form, sends it to a view and saves it. I need it to return me to the same template that has the table with the updated data. Currently it redirects me to the template but without showing me the datatable With return redirect it returns me to the original page without showing me anything With return render it shows me the datatable, but it changes the URL What am I doing wrong? Sorry for my English, I'm a junior View def delete_itemresumen(request, id): if request.method == "POST": ..... ..... ..... coleccion = Auxiliarresumen.objects.filter( Q(mes__icontains=mes) & Q(anio__icontains=anio) & Q(codcuentabanco=codban) ).distinct() form = RegistroBuscarResumen(initial={'accion':'buscar', 'id_codcuentabanco':codban, 'id_periodo':camp2}) return redirect("/bancos/procesarresumen") #or return render(request, 'bancos/procesarresumen.html', {'form': form, 'colecc': coleccion}) And HTML {% if colecc %} <table id="Listaitems" class="table table-hover table-sm text-left" style="white-space: nowrap; overflow-x: auto;" > <thead class="thead-light"> <tr> <th scope="col">Fecha</th> <th scope="col">Concepto</th> <th scope="col">Subconcepto</th> <th scope="col">Observacion</th> <th scope="col">Importe</th> <th scope="col">C/D</th> <th scope="col">Acciones</th> </tr> </thead> <tbody center> {% for col_obj in colecc %} <tr> <!-- <td<th scope="row">{{col_obj.fecha}}</th> --> <td class="h5 small">{{col_obj.fecha}}</td> <td class="h5 small">{{col_obj.codsubconcepto.codconcepto.descripcion}}</td> <td class="h5 small">{{col_obj.codsubconcepto.descripcion}}</td> <td class="h5 small">{{col_obj.descripcion}}</td> <td class="h5 small">{{col_obj.importe}}</td> <td class="h5 … -
Caddy Docker compose breaks when adding internal network
I'm Dockerizing my Django web application that uses a postgres db. Served over Caddy. Using caddy-docker-proxy I was able to get my django container/web app working with Caddy. But then when I added my postgres db to my compose file, Caddy no longer redirected my domain to django. ]1 Instead I get a Not Found. Here's my full docker compose file version: "3.7" services: web: build: . command: sh -c "gunicorn notobackend.wsgi:application --bind 0.0.0.0:8000" restart: always ports: - "8000:8000" expose: - 8000 environment: - POSTGRES_DB=supadb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres networks: - caddy - internal container_name: web depends_on: - db links: - db:db labels: caddy: supa.blog caddy.reverse_proxy: "{{upstreams 8000}}" env_file: - .env db: container_name: db image: postgres:latest restart: always expose: - 5432 ports: - 5432 environment: - POSTGRES_DB=supadb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - './data/db:/var/lib/postgresql/data' networks: - internal caddy: image: lucaslorentz/caddy-docker-proxy:ci-alpine ports: - 80:80 - 443:443 environment: - CADDY_INGRESS_NETWORKS=caddy networks: - caddy volumes: - /var/run/docker.sock:/var/run/docker.sock - caddy_data:/data restart: unless-stopped networks: caddy: external: true internal: external: false driver: bridge volumes: caddy_data: {} If I remove the "internal" network from the db service, Caddy correctly serves my django web app but now I get a 500 server error since I don't have my … -
Django ModuleNotFoundError: No module named 'model_db' using django.setup() outside django project
Im trying to use django ORM on a project, im using django 5.0.1, i read to acomplish i need this configuration, this would be on main.py: the link import django from django.conf import settings from DATABASE.Django_ORM.Django_ORM import settings as st settings.configure(default_settings=st, DEBUG=True) django.setup() #Importing Models from DATABASE.Django_ORM.model_db import models However it returns a Error: ModuleNotFoundError: No module named 'model_db' model_db is the app i create on django here is the settings.py: from pathlib import Path import os # 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/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'model_db', ] 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 = 'Django_ORM.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 = 'Django_ORM.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / … -
Installing Django-tailwindCSSS fails on tailwind strart
I'm installing Django-Tailwind following the instructions: https://django-tailwind.readthedocs.io/en/latest/installation.html The Django part works but the part that updates the CSS by runniong the command" "python manage.py tailwind start" fails. the node that executed the command in, package.json, "dev": "tailwindcss -i ./src/styles.css -o ../static/css/dist/styles.css -w", fails with a message that ends with: "Object.loadConfig (D:\DjangoTailwind__Starter\node_modules\tailwindcss\lib\cli\bu il\plugin.js:135:49) {'code: 'MODULE_NOT_FOUND', requireStack: [ 'D:\DjangoTailwind__Starter\src\djtailwind\theme\static_src\tailwind.config.js ']} I tried running: "npm install -D tailwindcss" but without success I' using Windowes 11 Node version 21.5.0 -
Installing mysqlclient python package
I want using mysql in django and I should install mysqlclient package in virtual env . My OS is ubuntu 20 . I run : pip install mysqlclient but I get this error : Collecting mysqlclient Using cached mysqlclient-2.2.1.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/home/caspian/Desktop/projects/django_project4/django-react1/React-Django-To-Do-App/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in main() File "/home/caspian/Desktop/projects/django_project4/django-react1/React-Django-To-Do-App/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/home/caspian/Desktop/projects/django_project4/django-react1/React-Django-To-Do-App/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-l_o48981/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-l_o48981/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-l_o48981/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "", line 155, in File "", line 49, in get_config_posix File "", line 28, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] note: … -
How Debug This error? "Method Not Allowed (POST)"
Hello. My friends, when I complete the form on the HTML side and send it to the Django side for validation. I get "Django Method Not Allowed (POST)" error. this is my model class ContactUs(models.Model): name = models.CharField(max_length=20, null=True, ) surname = models.CharField(max_length=20, null=True, ) email = models.EmailField(max_length=30, null=True, ) subject = models.CharField(max_length=20, null=True, ) text = models.TextField(null=True, ) this is my form class ContactModelForm(forms.ModelForm): class Meta: model = ContactUs fields = \['name', 'email', 'surname', 'subject', 'text'\] widgets = { 'name': forms.TextInput(), 'surname': forms.TextInput(), 'email': forms.EmailInput(), 'subject': forms.TextInput(), 'text': forms.Textarea(),} This my view,this is not a complete view, it is just for testing class ContactView(View): def get(self, request): form = ContactModelForm() return render(request, 'contact/contact_us.html', {'forms': form}) def post(self, request): form = ContactModelForm(request.POST)`` if form.is_valid(): form.save() return redirect('home') return render(request, 'contact/contact_us.html', {'forms': form}) -
Is it wise to construct a custom string (combination of entity, year and alphanumeric) to have as a primary key for a postgres database in Django?
I'm working on creating a Django backend for an application and I want the primary key of our entities to fulfil certain criteria. First criteria is that it is always 10 characters long so that it is easy to read and share verbally if needed. Second criteria is that it always follows the same format:- First 2 characters => Code for the entity (for example "US" is for User records, "TO" is for topics, "BO" for books etc.) so that anyone can easily say what a certain ID is for Second 2 characters => Year of the date of creation ('24', '23 etc.) Remaining 6 characters are randomly generated alphanumeric characters I've written the following code to generate the id:- def auto_increment_id(): alphanumeric_chars = string.ascii_letters + string.digits last_chars = ''.join(random.choice(alphanumeric_chars) for _ in range(6)) user_id = 'US' + str(datetime.date.today().year)[2:] + str(last_chars) return user_id And I have it setup in the user model like this class User(models.Model): id = models.CharField(max_length=10, primary_key=True, default=auto_increment_id, editable=False) My question is, will this lead to performance issues or other issues as we scale up? Is this a wise setup? -
Which database is more reliable Postgres or MySQL? [closed]
I am currently using a Postgres database, but I am encountering issues such as tables getting dropped automatically. As a result, I have concerns about the reliability of Postgres. What is you opinion ? Here is the link to the issue of table getting dropped. link I would like know which database should I choose ? -
Connecting an old MySQL server to the latest Django installation
I'm making a Django project that connects to an external MySQL database for a college project. The problem is that the database is outdated, and I keep getting the error message, "MySQL 8.0.11 or later is required (found 5.6.40)." I cannot update the database server and I would like to keep using the latest version of Django. If I were to create a middleware to convert the response from the database to a format readable to the Django 5.0.1, what would be the topics I would need to learn? I added the external database to the settings.py along with the main database. I also used connections from django.db to make queries so I would not have to add the entire database to models.py. -
Cannot generate instances of abstract factory (Django factory_boy)
this factories: `import factory from .models import * from factory.faker import * FAKE = faker.Faker(locale = 'ru_RU') class RoleFactoryManager(factory.django.DjangoModelFactory): class Meta: model = Role abstract = False role_name = 'manager' class RoleFactoryAdmin(factory.django.DjangoModelFactory): class Meta: model = Role abstract = False role_name = 'admin' class RoleFactoryUser(factory.django.DjangoModelFactory): class Meta: model = Role abstract = False role_name = 'user' class ClientFactory(factory.django.DjangoModelFactory): class Meta: model = Client abstract = False client_surname = factory.Faker('second_name') client_name = factory.Faker('first_name') client_date_of_registration = factory.Faker('date') client_email = factory.LazyAttribute(lambda a: '{}.{}{}@gmail.com'.format(a.client_surname, a.client_name, a.client_id).lower()) client_phone = factory.Faker('phone_number') client_photo = ('/images/profile_photo.png') ` this models: `from django.db import models class Role(models.Model): role_id = models.AutoField(primary_key=True) role_name = models.CharField(max_length=30, null=False) class Client(models.Model): client_id = models.AutoField(primary_key=True) client_surname = models.CharField(max_length=30, null=False) client_name = models.CharField(max_length=30, null=False) client_date_of_registration = models.DateField(null=False) client_email = models.CharField(max_length=99, null=False) client_password = models.CharField(max_length=99, null=False) client_phone = models.CharField(max_length=11, null=False) client_photo = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.client_surname} {self.client_name}'` and i get this for all of this factories: error is factory.errors.FactoryError: Cannot generate instances of abstract factory RoleFactoryManager; Ensure RoleFactoryManager.Meta.model is set and RoleFactoryManager.Meta.abstract is either not set or False. how to fix it i tried to indicate the model specifically, change imports and etc -
django form resubmitted upon refresh pag
After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that. How can I fix this ? Here's my views: from django.shortcuts import render from django.http import HttpResponse from free.models import contact `def index(request):` `if request.method == 'POST':` `fullname = request.POST.get('fullname')` `email = request.POST.get('email')` `message = request.POST.get('message')` `en = contact(fullname=fullname, email=email, message=message)` `en.save()` `return render(request, 'index.html')` -
Why paginating a ListView in django does not work?
I am doing the CS50W, the Network project, when I want to move to next / go back to the pagination of my web. Nothing happened. I tried to debug the view.py file, anytime I click the next or previous button in script.js , it all returned page_number as none in views.py . I have no idea why this happened. Can you guys help me? Here are the code in my views.py : def index(request): return render(request, "network/index.html") def allPosts(request): # Get all posts data - json allPosts = Post.objects.all() # Return emails in reverse chronologial order allPosts = allPosts.order_by("-timestamp").all() # Show 2 contacts per page. paginator = Paginator(allPosts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # return json all posts data = { 'posts': [post.serialize() for post in page_obj], 'page': { 'has_previous': page_obj.has_previous(), 'previous_page': page_obj.has_previous() and page_obj.previous_page_number() or None, 'has_next': page_obj.has_next(), 'next_page': page_obj.has_next() and page_obj.next_page_number() or None, 'num_pages' : page_obj.paginator.num_pages, 'current_page' : page_number } } return JsonResponse(data, safe=False) Code in my script.js file: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('.showallPosts').addEventListener('click',showallPosts); showallPosts(); }); function showallPosts(){ // Clear out composition field document.querySelector('#allPosts-view').value = ''; // Show the mailbox name document.querySelector('#allPosts-view').innerHTML = ` <h3>All Posts</h3> `; // Get … -
KeyError: 'fields', but key 'fields' is works at the same time
This is kind of weird: The print wint ex_pur['fields'] is working, and at the same time I have a KeyError: 'fields' abote this print(). Halp me please to understand what I'm doing wrong. Thank you! ... try: existed_purchases_queryset = Purchases.objects.filter(name__in=purchases_names, list_id=list_id) existed_purchases = serializers.serialize('python', existed_purchases_queryset) response["existed"] = existed_purchases print(f"----------------\n{existed_purchases = }\n----------------") existed_purchases_names = [pur['fields']['name'] for pur in existed_purchases] except Purchases.DoesNotExist: print("Все позиции новые.") for purchase in purchases: print(f"{type(existed_purchases[0]) = }") purchases_serializer = PurchaseAddSerializer(data=purchase) do = False if purchase['name'] in existed_purchases_names: for ex_pur in existed_purchases: print(f"----------------\n{('description' in **ex_pur['fields']**.keys()) = }\n----------------") if ex_pur['fields']['name'] == purchase['name']: ... ---------------- ('description' in ex_pur['fields'].keys()) = True ---------------- ---------------- ('description' in ex_pur['fields'].keys()) = True ---------------- ---------------- ('description' in ex_pur['fields'].keys()) = True ---------------- Internal Server Error: /purchases/add/ Traceback (most recent call last): File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\views\decorators\csrf.py", line 6 5, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\rest_framework\views.py", line 509, in d ispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\rest_framework\views.py", line 469, in h andle_exception self.raise_uncaught_exception(exc) File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\rest_framework\views.py", line 480, in … -
Internal server error on cmd,TemplateDoesNotExist at / index.html
I'm working on building a web app using Django and encountering the following error: Internal Server Error: / Traceback (most recent call last): File "D:\New folder\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\core\home\views.py", line 10, in home return HttpResponse(render(request, 'index.html')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html' path: D:\New folder\core\home\template file name:index.html basic html code D:\New folder\core file name = setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] EXTERNAL_APPS = [ 'home', ] INSTALLED_APPS += EXTERNAL_APPS file name:views.py code: from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'index.html')) def success_page(request): print("* "*10) return HttpResponse("""<h1>Page has Been created successfully</h1> </br> <hr> <p1> Hello world</p1>""") D:\New folder\core file name:urls.py code: from django.contrib import admin from django.urls import path from home.views impor urlpatterns = [ path('admin/', admin.site.urls), path('', home, name="home"), path('Success-page',success_page,name ="success_page") ] 'tried many approaches from stack over flow still same error. help me fixing this … -
Django model structure for question with type and subtype
is this type of model schema okay i have a question which will for sure have a type but the subtype is optional class QuestionType(models.Model): question_type = models.CharField(max_length=255) def __str__(self): return self.question_type class QuestionSubType(models.Model): question_type = models.ForeignKey(QuestionType, on_delete=models.CASCADE) question_sub_type = models.CharField(max_length=255) class Question(QuestionAbstractModel): chapter = models.ForeignKey(Chapter, blank=True, null=True, on_delete=models.CASCADE) type = models.ForeignKey(QuestionType, on_delete=models.CASCADE, blank=False) type_subtype = models.ForeignKey(QuestionSubType, on_delete=models.CASCADE, blank=True, null=True) solution_url = models.URLField(max_length=555, blank=True) def __str__(self): return f" {self.chapter.subject.grade} {self.chapter.subject.name} {self.chapter.name} {self.type}" is this model schema okay or can i improve it in any way -
Large number of rejected connections in memcached using django
I'm using Django-4.6.2 with memcached-1.5.22. The Django Cache settings (django.conf.settings.CACHES) are as follows: { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211' } } memcached is configured to use 1GB of memory (-m 1024), uses port 12111 (-p 11211), listens to localhost (-l 127.0.0.1) and has a maximum object size of 32MB (-I 32M). Despite this, there seem to be a large number of rejected connections in memcached stats (obtained via telnet): STAT max_connections 1024 STAT curr_connections 1 STAT total_connections 2462353 STAT rejected_connections 2462352 STAT connection_structures 11 Django is configured with wsgi, with processes=12, threads=12. Is this large number of rejected connections normal? What is the likely cause?