Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django per-site cache is not working properly
I'm facing some difficulties caching my website (JS, CSS, fonts, images). When I use lighthouse, I got these results [Cache TTL are all None] while I'm already applying the per-site caching as described in Django documentation. `MIDDLEWARE = [ ... 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ... ] CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 2 592 000 # for 1 month ` Is there any help in order to well cache the website? Tech used: Python 3.8 Django 3.2 Deployed through CPanel Thanks -
Get data from form without submit button Django
I have Django form like this,how i can get data without submit? class TestForm(forms.Form): cod = forms.CharField(max_length=6) class Meta: fields = ('cod',) Maybe it is made with AJAX or WebSocket? Thanks! -
how to fix error occure during installing mysqlclient for django in ubantu?
I am trying to install mysqlclient and got the following error. I am using Ubuntu 20.04 LTS I also did update and upgrade commands. My mysql password is toor mysql -u root -p toor (cc_env) amol@amol-Ideapad-320:~/My Code/Python/Project$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-2erfc_zu/mysqlclient_02a7d23804a54d6dafa6098aa7d9f18f/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-2erfc_zu/mysqlclient_02a7d23804a54d6dafa6098aa7d9f18f/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-2erfc_zu/mysqlclient_02a7d23804a54d6dafa6098aa7d9f18f/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. pip list (cc_env) amol@amol-Ideapad-320:~/My Code/Python/Project$ pip list Package Version … -
Only the first Django site to be loaded works
I recently submitted a problem to stackoverflow titled Django infinite loading after multiple requests on apache using mod_wsgi. Anyways, I have recently changed a lot of that code and now I have a new problem. The first Django website I request works, however, the second one points to the first one I loaded and gives the response DisallowedHost because obviously it is trying to access that Django application with a different domain name. I obviously want it to do that it should do so if anyone can help me that would be great. Here is all my code. Vhosts LoadFile "C:/Users/taber/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310" ################################################################################################## # ASTINARTS.UK.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName astinarts.uk.to SSLEngine on SSLCertificateFile "conf/astinarts/astinarts.uk.to-chain.pem" SSLCertificateKeyFile "conf/astinarts/astinarts.uk.to-key.pem" WSGIApplicationGroup %{GLOBAL} Alias /static "C:/xampp/htdocs/astinarts/static" <Directory "C:/xampp/htdocs/astinarts/static"> Require all granted </Directory> Alias /media "C:/xampp/htdocs/astinarts/media" <Directory "C:/xampp/htdocs/astinarts/media"> Require all granted </Directory> Alias /.well-known "C:/xampp/htdocs/astinarts/.well-known" <Directory "C:\xampp\htdocs\astinarts\.well-known"> Require all granted </Directory> Alias /sitemap.xml "C:/xampp/htdocs/astinarts/sitemap.xml" Alias /robots.txt "C:/xampp/htdocs/astinarts/robots.txt" <Directory "C:/xampp/htdocs/astinarts/astinarts"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/astinarts/astinarts/wsgi.py" <Directory "C:/xampp/htdocs/astinarts/astinarts"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ################################################################################################## # NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName neostorm.us.to SSLEngine on SSLCertificateFile "conf/ssl.crt/neostorm.us.to-chain.pem" SSLCertificateKeyFile "conf/ssl.key/neostorm.us.to-key.pem" WSGIApplicationGroup %{GLOBAL} Alias /static "C:/xampp/htdocs/neostorm/static" <Directory … -
django ckeditor upload not working in production
django settings: CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_RESTRICT_BY_DATE = False CKEDITOR_UPLOAD_PATH = 'uploads/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_ROOT = os.path.join(BASE_DIR, "attachments") STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'), ) STATIC_URL = f"{FORCE_SCRIPT_NAME}/backend/static/" MEDIA_URL = f"{FORCE_SCRIPT_NAME}/backend/attachments/" urls: urlpatterns = [ path('admin/filebrowser/', site.urls), path("grappelli/", include("grappelli.urls")), path('admin/', admin.site.urls), path("api/", include(api_urlpatterns)), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=settings.DEBUG) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT, show_indexes=settings.DEBUG) if settings.DEBUG: import debug_toolbar urlpatterns = [ path("__debug__/", include(debug_toolbar.urls)), ] + urlpatterns nginx: location /project_name/ { set $service project_name; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://$service; client_max_body_size 16m; } In dev all works, upload and browse, but in prod with not (AH00128: File does not exist: /var/www/html/project_name/ckeditor/upload). I try add alias/root to nginx config, change ckeditor path to re_path(r'^ckeditor/', include('ckeditor_uploader.urls')) and still nothing( -
What happens line by line after I register a model in django
I'm new to programming and I don't really understand what's going on line by line in the code For example: to register a model in Django, we can register the class “class Genre(models.Model)” and specify only one field, for example “models.Charfield.” In turn, the parent class “Model(metaclass=ModelBase) (django.db.models.base)” contains about 50 methods. Most of them are private Questions: Were these 50 methods called when I registered the model? If “yes”, which line of code is responsible for this call? Or which principle of OOP? Could you recommend any article or book to delve into this topic? Thanks in advance! -
how can we filter objects of data from database on the basics of latest? python [duplicate]
I want only 3 database objects which are latest in database, table from django table. like if we have 20 in whole table , so the code will give only three which are latest as per date. -
Custom template tag wont assign to {% with %} context
I'm in need of a custom tag where multiple keyword arguments can be passed in for the purpose of creating an unique id for a given object instance. Whatever string the tag returns it assigns the string as a context variable to the included template. Yet the id context variable remains empty. In this case, the ids for the SVG elements only return the hardcoded strings upvote_ and downvote_. How can I fix this so that the id context variable is interpolated into the string of the SVG id attributes? An example being: upvote_queston101 {% for answer in question.answers.all %} {% include "./posted.html" with post=answer id=set_id question=question.id answer=answer.id %} {% endfor %} <div class="rating_box"> <div class="vote"> <svg id="upvote_{{ id }}" class="vote_button"> </svg> <p>{{ post.score }}</p> <svg id="downvote_{{ id }}" class="vote_button"> </svg> </div> <p class="post_body_content">{{ post.body }}</p> </div> from django import template register = template.Library() @register.simple_tag def set_id(*args, **kwargs): if kwargs['question'] and kwargs['answer']: q_id, a_id = kwargs['question'], kwargs['answer'] return f"question{q_id}_answer{a_id}" q_id = kwargs['question'] return f"question{q_id}" -
Flutter Web on Firebase hosting refused to make API Calls
I have a Flutter Web application that I have deployed on Firebase Hosting. I have a Django backend that I have deployed on an EC2 instance and is running on http. I have CORS enabled in the backend, tried accessing endpoints via browsers and it works just fine. But, when I try to make the same call using FlutterWeb, it fails. And error type of blocked:mixed content appears. (See image below) I want to call those HTTP endpoints and I don't want an SSL certificate mess because this is just a college project. How do I fix this? I am using Dio on Flutter Web to make requests. What would be causing this problem? -
How to pass values multiple html file by render_to_string class in django?
This is my code when I delete a product from header_3.html everything fine but I want to do the same delete work on the cart page. It working but need to reload the page. how to pass multiple html file names through render_to_string? selected_item_html = render_to_string( 'header_3.html', { 'num_of_cart': cart_value, 'total_cart': total_cart, 'subtotal_amount': cart.get_subtotal_price(), } If I replace header_3.html with cart.html it working fine but I want both header_3.html and cart.html -
No Django settings specified. Unknown command: 'createsuperuser' Type 'manage.py help' for usage
I am trying to create a superuser through createsuperuser command in manage.py console is throwing an error "No Django settings specified. Also tried in python console by runninf python manage.py createsuperuser Unknown command: 'createsuperuser' Type 'manage.py help' for usage." I AM USING PYCHARM settings.py """ Django settings for MovieFlix project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-#*8cdy*ul906(s4ei#g7h17)vv%)#0s5b##weupzn-&ct@ylez' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.2.12', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Core.apps.CoreConfig', 'movie.apps.MovieConfig', ] 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 = 'MovieFlix.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'Core/templates')] , '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 = 'MovieFlix.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES … -
File C:\ProjectName\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system
Allow Windows PowerShell to Execute ScriptsPermalink. Type the following command in the PowerShell admin window to change the execution policy: set-executionpolicy remotesigned then enter "Y" or "A". Now you can activate your Django project. -
In Django have written a clear code everything good but still the css does not display on the webscreen and i am using python 3.10 and django 4
Am using Python 3.10 And django 4.0.3 I tried to change my base dir but still did not work Firstly it was STATIC_URL = ' /static/' STATICFILES_DIR=[os.path.join(BASE_DIR),] Then secondly i tries this STATIC_URL = ' /static/' STATICFILES_DIR = [os.path.join(BASE_DIR),] STATIC_ROOT = os.path.join (os.path.dirname (BASE_DIR),"static") -
Getting top 3 most enrolled course by students
I am building a website where an instructor can create courses and students can enroll the courses. I wanted to display top 3 most enrolled courses/popular courses. I tried to filter the courses that the instructor has, find the number of students that has enrolled to the courses and ordered them by descending which means it will display from highest to lowest number of enrolled students per course. It will then display only the top 3 most enrolled courses. However, my code does not work. Please help T.T models.py class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) enrollment_date = models.DateField(auto_now_add=True, null = True) class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.TextField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.TextField(max_length=2500, null = False) timeline_budget = models.TextField(max_length=250, null = False) req_prerequisite = models.TextField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) views.py … -
Formatting Django test output
I would like to format the output of test output in my Django app because I have a lot of tests and at this point there is so much output that it is unreadable. I have read Django docs on logging and I understand that I would need to configure LOGGING dict in my settings and use Loggers, Handlers, and Formatters, along with Python's native logging lib doing majority of heavy lifting. The problem is that I don't know where to begin. Here is what I would like to achieve in terms of output: TOTAL tests run: 123 Failed: 4 Skipped: 5 Passed: 114 APP2 tests run: 34 Failed: 0 Skipped: 1 Passed: 114 APP3 tests run: 67 Failed: 5 Skipped: 0 Passed: 62 According to Django docs logging is fairly customizable with something like this (taken from official docs, closer to the bottom of the page): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], … -
clean some json objects from google autocomplete api
I am currently working at a project which require to clean the data fetched from google autocomplete API. Most of you may have seen json response from that like below: [ "jarvis", [ "jarvis full form", "jarvis song", "jarvis ai", "jarvis meaning", "jarvis iron man", "jarvis in python", "jarvis technology", "jarvis meaning in hindi" ], [ "", "", "", "", "", "", "", "" ], [], { "google:clientdata": { "bpc": false, "tlw": false }, "google:suggestrelevance": [ 601, 600, 555, 554, 553, 552, 551, 550 ], "google:suggestsubtypes": [ [ 512, 433 ], [ 512 ], [ 512 ], [ 512, 433 ], [ 512, 433 ], [ 512 ], [ 512 ], [ 512 ] ], "google:suggesttype": [ "QUERY", "QUERY", "QUERY", "QUERY", "QUERY", "QUERY", "QUERY", "QUERY" ], "google:verbatimrelevance": 1300 } ] now what I need to do is to clear those google litters , [ "", "", "", "", "", "", "", "" ], [], { "google:clientdata": { "bpc": false, "tlw": false }, "google:suggestrelevance": [ 601, 600, 555, 554, 553, 552, 551, 550 ], "google:suggestsubtypes": [ [ 512, 433 ], [ 512 ], [ 512 ], [ 512, 433 ], [ 512, 433 ], [ 512 ], [ 512 ], [ … -
How do you print the Django SQL query for an aggregation?
If I have a django queryset print(queryset.query) shows me the SQL statement so I can validate it. But with aggregations they never return a queryset. How do you print those queries out. I guess I can turn on debug logging for the ORM and find them that way but it seems like I should be able to get it right before the execution engine sends it off to postgres..... -
The term 'mkvirtualenv' is not recognized as the name of a cmdlet, function, script file,or operable program
Below step by step answer: To install virtual environment using use below pip command: *py -m pip install --user virtualenv* Then create new environment: *py -m venv projectName* Then you have to activate your virtual environment: *.\projectName\Scripts\activate* Once done with activating virtual environment, You’ll see “(myproject)” next to the command prompt. -
running multiple django processes concurrently
I am using a package to send request needed to the front end, but I discovered that the package was blocking all other operations taking place in the server even the loading of a new page, so the server does not respond to any request until the package is through. Please how can I get the server to run multiple processes while the package is running. This is my code from django_eventstream import send_event#this is the package send_event('test', 'message', "Time spent processing the data "+ x+" mins"))// No other operation responds while this one is running -
How i can check boolean field in Javascript during the submitting of the form in a Django project
I want to check the char fields of my form if they are filled otherwise a msg will displayed, in same way I want to check 2 BooleanField exist in the same form, if both of them is false a message labeled will be displayed also, The issue that the first condition it works normally and show me the msg "Form incomplete. Please, fill out every field!" but the "second condition(if('#a_model1' === false && '#a_model2' === false )) it doesn't give me a result where i want to check both of the BooleanField if they are false. Here is my code: javascript code: <script language="JavaScript"> function mySubmitFunction(e) { var profession = $("#id_profession").val(); var taille = $("#id_taille").val(); let myVars = [profession, taille] if (myVars.includes("") || myVars.includes("Empty")) { document.getElementById('submit_label').innerHTML = 'Form incomplete. Please, fill out every field!'; e.preventDefault(); someBug(); return false; if('#a_model1' == false && '#a_model2' == false ){ document.getElementById('submit_label2').innerHTML = 'Check one of the model please in Models Section!'; e.preventDefault(); someBug(); return false; } } else { return true; } } </script> the boolean fields in the template.html: <span id="a_model1" >{{ form.model1}} </span> <span id="a_model2" >{{ form.model2}}</span> in models.py: model1 = models.BooleanField(verbose_name=" model1") model2 = models.BooleanField(verbose_name=" model2") so i want to … -
How to use row_factory with a non-default Sqlite database in Django
In the simple Sqlite3 code below, in order to use row_factory, I understand I need a connection object. However, when using a non-default database ("sqlite3_db" set up in DATABASES in settings.py), I can't figure out how this is done. def index_sqlite(request): from django.db import connections import sqlite3 cursor = connections["sqlite3_db"].cursor() #connection.row_factory = sqlite3.Row ==> how to access the connection object?? sql = "SELECT title, rating FROM book_outlet_book ORDER BY title" cursor.execute(sql) book_list = [item for item in cursor.fetchall()] return render(request, "book_outlet/index.html", { "title": "Some title", "books": book_list }) This code produces a list of tuples as expected, but I am after a "dictionary cursor" so I can do things like reference book_list[3].title (without using a model). -
How to discard and rebuild a postgres container using docker compose
So I have a docker-compose file that has 2 services app and db version: '3.9' services: app: build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - .:/app - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme I changed the Django model, deleted the old migration files (which I shouldn't have done) and then did a 'manage.py migrate --fake zero' and now on migrating I get an obvious error that the table already exists in the Postgres container. app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute app_1 | return super().execute(sql, params) app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute app_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers app_1 | return executor(sql, params, many, context) app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute app_1 | return self.cursor.execute(sql, params) app_1 | File "/py/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ app_1 | raise dj_exc_value.with_traceback(traceback) from exc_value app_1 | File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 83, in _execute app_1 | … -
no module named contact error Python Django
https://github.com/MetsxxFan01/Python-Django that website should have all the code. modulenotfounderror: no module named 'contact' -
How to run the qcluster process in production (Django-q)?
I have a Django webapp. The app has some scheduled tasks, for this I'm using django-q. In local development you need to run manage.py qcluster to be able to run the scheduled tasks. How can I automatically run the qcluster process in production? I'm deploying to a Digital Ocean droplet, using ubuntu, nginx and gunicorn. -
Bad Request creating Automation Account in Azure Python SDK
I'm trying to create a new AutomationAccount using Python SDK. There's no problem if I get, list, update or delete any account, but I'm getting a BadRequest error when I try to create a new one. Documentation is pretty easy: AutomationAccountOperations Class > create_or_update() #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from azure.identity import AzureCliCredential from azure.mgmt.automation import AutomationClient credential = AzureCliCredential() automation_client = AutomationClient(credential, "xxxxx") result = automation_client.automation_account.create_or_update("existing_rg", 'my_automation_account', {"location": "westeurope"}) print(f'Automation account {result.name} created') This tiny script is throwing me this error: Traceback (most recent call last): File ".\deploy.py", line 10 result = automation_client.automation_account.create_or_update("*****", 'my_automation_account', {"location": "westeurope"}) File "C:\Users\Dave\.virtualenvs\new-azure-account-EfYek8IT\lib\site-packages\azure\mgmt\automation\operations\_automation_account_operations.py", line 174, in create_or_update raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) azure.core.exceptions.HttpResponseError: (BadRequest) {"Message":"The request body on Account must be present, and must specify, at a minimum, the required fields set to valid values."} Code: BadRequest Message: {"Message":"The request body on Account must be present, and must specify, at a minimum, the required fields set to valid values."} I've tried to use this method (create_or_update) on a different sdk like powershell using same parameters and it worked. Some thoughts?