Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fix my link in modal class on Bootstrap 5?
I have a template to show posts and each post has post.id. Also there is a button to open modal and "yes" button must delete post with post.id that I clicked. But when I do this it deleting the first post on current page instead of the right one I clicked before. ... <div class="col-md-9"> {% for post in page %} <div class="card-body"> <p class="card-text p-2"> <a class="link text-dark" href="/profile/{{post.author.username}}/"><strong class="d-block text-dark">@{{profile_user.username}}</strong> </a> {{post.text}} {% load thumbnail %} {% thumbnail post.image "960x339" crop="center" upscale=True as im %} <img class="card-img" src="{{ im.url }}"> {% endthumbnail %} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a class="btn btn-sm text-muted" href="/profile/{{profile_user.username}}/{{post.id}}/" role="button"> ... </a> {% if user.username == profile_user.username %} <a class="btn btn-sm text-muted" href="/profile/{{profile_user.username}}/{{post.id}}/edit" role="button">...</a> <!-- Button trigger modal --> <button type="button" class="btn btn-sm text-muted" data-bs-toggle="modal" data-bs-target="#exampleModal"> ... </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Delete post?</h1> <button type="button" class="btn btn-sm text-muted" data-bs-dismiss="modal" aria-label="Close">...</button> </div> <div class="modal-footer"> <button type="button" class="btn btn secondary" data-bs-dismiss="modal">NO</button> <a role="button" class="btn btn-primary" href="/profile/{{profile_user.username}}/{{post.id}}/delete">YES</a> <!-- TODO Fix id problem--> </div> </div> </div> </div> {% endif %} </div> <small class="text-muted">{{post.pub_date}}</small> </div> </div> {% endfor %} ... I … -
No handlers could be found for logger "cuckoo"
Error I am running the Cocosandbox project. But I get this error when running Coco command Oops! Cuckoo failed in an unhandled exception! Sometimes bugs are already fixed in the development release, it is therefore recommended to retry with the latest development release available https://github.com/cuckoosandbox/cuckoo If the error persists please open a new issue at https://github.com/cuckoosandbox/cuckoo/issues === Exception details === Cuckoo version: 2.0.7 OS version: posix OS release: Ubuntu 22.04 jammy Python version: 2.7.18 Python implementation: CPython Machine arch: x86_64 Modules: alembic:1.0.10 androguard:3.0.1 argparse:1.2.1 attrs:21.4.0 beautifulsoup4:4.5.3 capstone:3.0.5rc2 cffi:1.15.1 chardet:2.3.0 click:6.6 colorama:0.3.7 configparser:4.0.2 contextlib2:0.6.0.post1 cryptography:3.3.2 cuckoo:2.0.7 django-extensions:1.6.7 django:1.8.4 dpkt:1.8.7 ecdsa:0.18.0 egghatch:0.2.3 elasticsearch:5.3.0 enum34:1.1.10 flask-sqlalchemy:2.4.0 flask:0.12.2 functools32:3.2.3.post2 future:0.18.3 gevent:1.2.2 greenlet:2.0.2 httpreplay:0.2.6 idna:2.10 importlib-metadata:2.1.3 ipaddress:1.0.23 itsdangerous:1.1.0 jinja2:2.9.6 jsbeautifier:1.6.2 jsonschema:3.2.0 mako:1.1.6 markupsafe:1.1.1 olefile:0.43 oletools:0.51 pathlib2:2.3.7.post1 peepdf:0.4.2 pefile2:1.2.11 pillow:3.2.0 pip:20.3.4 pycparser:2.21 pycrypto:2.6.1 pyelftools:0.24 pyguacamole:0.6 pymisp:2.4.106 pymongo:3.0.3 pyopenssl:21.0.0 pyrsistent:0.16.1 python-dateutil:2.4.2 python-editor:1.0.4 python-magic:0.4.12 python:2.7.18 pythonaes:1.0 requests:2.13.0 roach:0.1.2 scandir:1.10.0 scapy:2.3.2 setuptools:44.1.1 sflock:0.3.10 six:1.16.0 sqlalchemy:1.3.3 tlslite-ng:0.6.0 typing:3.10.0.0 unicorn:1.0.1 urllib3:1.26.18 wakeonlan:0.2.2 werkzeug:1.0.1 wheel:0.37.1 wsgiref:0.1.2 yara-python:3.6.3 zipp:1.2.0 No handlers could be found for logger "cuckoo" -
Django TypeError: fromisoformat: argument must be str
enter image description here class UserConfirmation(BaseModel): TYPE_CHOICES = ( (VIA_PHONE, VIA_PHONE), (VIA_EMAIL, VIA_EMAIL) ) code = models.CharField(max_length=4) verify_type = models.CharField(max_length=31, choices=TYPE_CHOICES) user = models.ForeignKey('users.User', models.CASCADE, related_name='verify_codes', db_constraint=False) expiration_time = models.TimeField(null=True) is_confirmed = models.BooleanField(default=False) def __str__(self): return str(self.user.__str__()) def save(self, *args, **kwargs): if not self.pk: if self.verify_type == VIA_EMAIL: self.expiration_tme = datetime.now() + timedelta(minutes=EMAIL_EXPIRE) else: self.expiration_tme = datetime.now() + timedelta(minutes=PHONE_EXPIRE) super(UserConfirmation, self).save(*args, **kwargs) -
Django single login page for both rest_framework and admin console
I am making a Django application which uses rest_frameworks (under urlpattern '/api') and the admin console (for user and group management, under urlpattern '/admin'). Currently they both have their own login page. I want both of them to use the same login page (a single login URL), and if the user successfully logs in, then if it is a superuser redirect to the admin console, and if not a superuser then redirect to '/foo'. I know you can insert a url pattern above the admin.site.urls to override its login (and logout) url patterns, but I want the login page to be '/login' not '/admin/login'. -
TemplateDoesNotExist at /home/ internal server error Django
my html file isn't displaying. folder path: D:\New folder\core\core\home View.py file in home app D:\New folder\core\core\home urls.py file in home app D:\New folder\core\core urls.py file in core project D:\New folder\core\core Settings.py file in core project index.html file in template which is in template file Tried every step help me solving this -
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')`