Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerize Django + mySql app: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)") error
I'm trying to dockerize my Django app which uses mySql but I'm facing some problems. It's the first time I use Docker so there may be something basic which I don't understand. Following some online tutorials, this is my Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install --upgrade pip && pip install -r requirements.txt RUN pip install mysqlclient COPY . /code/ And this is my docker-compose: version: '3' services: db: image: mysql:8 ports: - '3306:3306' environment: MYSQL_DATABASE: 'database_name' MYSQL_USER: 'django' MYSQL_PASSWORD: 'django-password' MYSQL_ROOT_PASSWORD: 'password' volumes: - .setup.sql:/docker-entrypoint-initbd.d/setup.sql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'mysql-db'), 'USER': os.environ.get('MYSQL_USER', 'mysql-user'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'mysql-password'), 'HOST': os.environ.get('MYSQL_DATABASE_HOST', 'db'), 'PORT': os.environ.get('MYSQL_DATABASE_PORT', 3306), } } And .env: MYSQL_DATABASE=database_name MYSQL_USER=django MYSQL_PASSWORD=django-password MYSQL_ROOT_PASSWORD=password MYSQL_DATABASE_HOST=db MYSQL_DATABASE_PORT=3306 To dockerize the app, I'm using Docker desktop in Windows 10. After I run: docker-compose up -d I see both containers (db and web) are running, however in the web container I see that django is not able to connect to mySql, as it gives me the error: django.db.utils.OperationalError: (2002, "Can't … -
How to retrieve and map through items of a specific category with Django and react
I'm trying to fetch items of a particular category that then map through the category in react app. I created an API with Django restframework that returns items of such category but using a post request. Here is the code: class ProductCategoryView(APIView): serializer_class = ProductSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = Product.objects.order_by('-dateCreated').filter(category__iexact=category) serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) For instance, let's say I have 3 categories of items in the database(textbooks, journals and novels). In the react frontend app, I want to retrieve only the textbooks, map through the array of textbooks and display each textbook without displaying any item from other categories. But I have challenges implementing it since I'm using post request. By passing a specific category to the body of the request I get items in that category returned. Is it possible to use get request and filter the items from the database such that I get only the items under the category called textbook? -
Django admin label style
I am trying to apply style on a calculated field in Django. I am able to change the color of the field but I do not know how to apply styles to the related label I am using the following code and I want to style "Total Cash" label @property @admin.display(description="Total Cash") def bar_total_cash(self): return format_html('<span style="color: red; font-weight: bold;">{}</span>', formats.localize(round(self.bar_cash_initial + self.bar_cash_dop + self.bar_cash_usd * self.usd_dop_rate + \ self.bar_cash_eur * self.eur_dop_rate + self.bar_cash_propina - self.bar_credit, 2), use_l10n=True)) -
QuerySet in Django by keywords
I need to display all hashtags that are similar in a QuerySet. But unfortunately, each tag has its own id and is tied to a separate article, but I can’t display information about whether there are articles with the same hashtag (lack of experience) tell me pls views.py class tags(DetailView): model = NewsDB template_name = 'navigation/tags.html' context_object_name = 'News' def get_context_data(self, *, object_list=None, **kwargs): articles = super(tags,self).get_context_data(**kwargs) articles['post'] = Hashtags.objects.filter(Hashtag=self.kwargs['pk']) return articles urls.py path('tags/<str:pk>',views.tags.as_view(),name='tag') models.py class NewsDB(models.Model): title = models.CharField('Название',max_length=300) text = models.TextField('Текст статьи') img = models.ImageField('Фото',upload_to='News',null='Без фото') avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT) date = models.DateField('Date', null=True, blank=True) time = models.TimeField('Time',null= True) def __str__(self): return self.title class Hashtags(models.Model): News=models.ForeignKey('NewsDB',on_delete=models.PROTECT) Hashtag=models.CharField('Хештег',max_length=30,null='Без темы') def __str__(self): return self.Hashtag -
Is it possible to implement when a person scans the qr code he automatically logged into the account on the web site
How can this be done? if possible. I'll be glad if you can tell me. I roughly understood how to create a qr code. But automatic registration via qr code don't know -
How to fix django-admin version 4.0.4 NOT detecting my migrations?
I am working with django-admin version 4.0.4 recently I delete all files and folders inside my migration folder and use makemigrations and migrate command. that works fine. But after that when I try to make changes add models OR change, makemigrations NOT detecting my changes. -
Project architectures differences for Django + Vuejs (or other) integration
I'm currently looking at project setups for a Django + Vuejs project (though I guess the question is likely just as valid for other frontends, react, svelte etc.). It seems that there are mainly 2 approaches that come up often, resulting in the following project structure: The frontend embedded within the Django project (perhaps as a git submodule): root ├── djangoapp ├── djangoproject ├── manage.py ├── requirements.txt ├── static ├── venv └── vueproject ├── node_modules ├── package.json ├── public └── src Another approach is to have them at the same level from project root, as 2 seperate projects actually (or I guess both could be git submodules to a "wrapper" project), so essentially: root ├── djangoproject │ └── <django files & folders> └── vueproject └── <vue files & folders> With the 2nd approach, it seems you basically just see Django as an API. Stuff like collectstatic does not (?) come into play. In development, you need a server up to serve Django's api, and a dev server for the vue frontend. With the 1st approach (if I understand correctly), seems that you build the Vue static files, and then manage all of that with Django's collectstatic/static files management. Seems the … -
Django post request for initial view
In Django I have a function def foo(): #(Here I want to call url: helloWorld with post request args) #I know there is libraries like Requests, but are there any django quicker methods? return HttpResponse("ok") and url: path('/path/to/url/', views.foo, name='helloWorld') -
django search human readable values
I am trying to write a query that searches the human readable values of an option list. class Book(models.Model): title = models.CharField(max_length=256) authors = models.CharField(max_length=256, default=None) GENRE = [ ('0', 'None'), ('1', 'Action-Adventure'), ('2', 'Autobigraphy'), ('3', 'Biography'), ('4', 'Classic'), ('5', 'Drama'), ('6', 'Fantasy'), ('7', 'Fiction'), ('8', 'Historical'), ('9', 'Mystery'), ('10', 'Non-Fiction'), ('11', 'Romance'), ('12', 'Science-Fiction'), ] genre = models.CharField(max_length=2, choices=GENRE, default='0') book_cover = models.ImageField(upload_to='covers/', default=None) description = models.TextField(default=None) added_by = models.CharField(max_length=256, default=None) date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.title and here is my search view. def search_books(request): if request.method == 'GET': query = request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups = Q(title__icontains=query) | Q(authors__icontains=query) | Q(genre__icontains=query) | Q(added_by__icontains=query) results = Book.objects.filter(lookups).distinct() context = {'book_list': results, 'submitbutton': submitbutton} return render(request, 'books/book_list.html', context) else: return render(request, 'books/book_list.html') else: return render(request, 'books/book_list.html') Is there any way to search the values of genre, such as 'Action-Adventure' instead of the numeric value? -
Error the current path match any of these
Whenever i try to load login,register page its showing Using the URLconf defined in loan.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] register [name='register'] logout [name='logout'] form [name='form'] predict [name='predict'] The current path, register/, didn’t match any of these How can i solve this issue from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('login', views.login, name="login"), path('register', views.register, name="register"), path('logout', views.logout, name="logout"), path('form', views.form, name="form"), path('predict', views.predict, name="predict"), ] from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth from .models import Prediction import joblib import pandas as pd from sklearn.preprocessing import scale from sklearn.impute import SimpleImputer res = 'X' # Create your views here. def index(request): return render(request, "index.html") def login(request): if request.method == "POST": name = request.POST['username'] pas = request.POST['password'] user = auth.authenticate(username=name, password=pas) if user: auth.login(request, user) print(user.is_authenticated) return redirect("/") else: messages.info(request, "User does not exist") return redirect("login") else: return render(request, "login.html") def register(request): if request.method == "POST": fname = request.POST['first_name'] lname = request.POST['last_name'] email = request.POST['email'] uname = request.POST['username'] pas1 = request.POST['password1'] pas2 = request.POST['password2'] if pas1 == pas2: if User.objects.filter(username=uname).exists(): messages.info(request, "Username already exists") return render(request, "register.html") elif User.objects.filter(email=email).exists(): messages.info(request, … -
Does Google App Engine allow file caching (using Django)?
I am seeing a problem that Django's file-based caching is not functional in Google App Engine. Ideally I want to use commands such as below to read/write from a Google Cloud Storage Bucket. output = cache.get(cacheKey) #or cache.set(cacheKey, output, timeout = 60*15) I have seen some articles on memcaching, but that is not what I need. Is it possible to combine Django's file-based caching with Google Cloud Storage? How do I perform this (and what permission settings are required?) -
Css is not reflected when deploying django on heroku
I wrote the code in settings.py as below, but the css was not reflected. I also ran $ heroku run python manage.py collectstatic, but when I looked at heroku run bash, there were no static files. Please tell me how to deal with it. settings.py from pathlib import Path import os MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] from socket import gethostname hostname = gethostname() if "User-MacBookAir.local" in hostname: DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ALLOWED_HOSTS = ['*'] else: DEBUG = False import dj_database_url db_from_env = dj_database_url.config() DATABASES = { 'default': dj_database_url.config() } ALLOWED_HOSTS = ['.herokuapp.com'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Intermittent connection issue between micro-services
I have two flask micro-services micro-service A: it in hosted in one remote server, endpoint for which is https://server_ip_A:5000/ from flask import Flask, jsonify import requests app = Flask(__name__) @app.route('/') def index(): try: response = requests.get("https://server_ip_B:5001/healthcheck", verify=False) return jsonify({'msg': response.data}) except Exception as e: return jsonify({'msg': e}) app.run(host='0.0.0.0', port=5000) micro-service B: it in hosted in other remote server, endpoint for which is https://server_ip_B:5001/ from flask import Flask, jsonify app = Flask(__name__) @app.route('/healthcheck') def index(): return jsonify({'msg': "running"}) app.run(host='0.0.0.0', port=5001) Both application is dockerized and deployed using gunicorn with --worker-class=gevent and nginx I observe sometimes micro-service A couldn't communicate with micro-service B, even though both the services are up and running. When micro-service A is not able to communcate with micro-service B, Error it throws is HTTPSConnectionPool(host='server_ip_B', port=5001): Read timed out. (read timeout=60) If communication is made, usually it returns response within 2 seconds. One of the solution I tried is retrying the https://server_ip:5001/healthcheck, if communication is not made. It works but increases the response time for users. What could be the reason? How can i make sure there is always a communication between micro-services without retrying, if both are up and running Thanks in advance! -
gcloud app deploy giving internal 500 error
We have a pythong/django/glcoud mysql db and a working website. A coworker managed the entire site left the company and now when we try to deploy small changes either it errors out "too many files" or we remove the venv folders and get an internal 500 server error on production which we migrate back our changes to before the latest deployment. -
How to link JavaScript page to django web app?
So I have a javascript file I'm trying to link to my html file. I've managed to connect css files to multiple html files so it seems like my static settings and such are working well however I get an error message : "Not Found: /item-store.js" (item-store.js is my JavaScript file). (BTW : My html file is named "item-store.html) I'm not sure how to fix the issue. Any ideas? Here is my html file : {% load static %} <!DOCTYPE html> <html lang="en"> <head> ...Code... </head> <body> ...Code... <script src="item-store.js"></script> </body> </html> A few lines of my settings.py file : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'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', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "templates"), ) MEDIA_ROOT = '' MEDIA_URL = '' I'll be active today every once in a while so i'll be able to clarify anything if needed or provide more information. Thank you for your time! -
The error of Django application crashed ngnix and the server
My Django application run well for a while, then I got 502 Bad Gateway, after a few hours, I am unable to ping the domain and use SSH to connect the server. My other application served by ngnix was also not available then. While if I didn't start the Django application, ther application served by ngnix would run steadily. So I guess it is the error of my Django application crashed ngnix and the server. After rebooting the server for serveral times, the server seems recovered then I can ping the domain and use SSH to connect the server. But after a while, the same problem would occurs again. I wonder how to fix the problem. Some diagnostic information since the start of the Django application to the end of the Nginx server provided below. The RAM usage is high during the process. The uwsgi log. https://bpa.st/FP7Q The Nginx error log. https://bpa.st/35EQ -
how to check isinstance for date in django python
I have date data in variable date_var as from django.db import models from datetime import datetime class Model: created_date = models.DateTimeField date_var = model.created_date.date() however when I check isinstance of c with datetime or with models.DateTimeField it returns false isinstance(date_var,datetime) // False isinstance(date_var,models.DateTimeField) // False what is the way to check if c is instance of date? -
Python Django Retrieve Value of others when ForeignKey is selected
If I explain my problem, I want to retrieve the objects value of a models inside another models when a ForeignKey is selected, maybe with the code is will be more easily to understand: the 1st models: class process(models.Model): Process = models.CharField(max_length=Lenght200) LeakValue = models.FloatField(verbose_name='Leak Value', default=0.00) ScreenValue = models.FloatField(verbose_name='Screen Value', default=0.00) date_added = models.DateTimeField(verbose_name='Date Added', auto_now_add=True) def __str__(self) -> str: return self.Process the 2nd models: class productsdefinition(models.Model): Products = models.CharField(max_length=Lenght200, default='NA') Process = models.ForeignKey(process, on_delete=models.CASCADE) LeakValue = models.ForeignKey(process, on_delete=models.CASCADE) ScreenValue = models.ForeignKey(process, on_delete=models.CASCADE) def __str__(self) -> str: return self.Products I didn't find something which help me or my search was wrong. When we create the object in the models process, we have a value in LeakValue & ScreenValue (we can take for example the default value 0.00). How i can retrieved it when on my models productsdefinition, I select the Process inside the ForeignKey? -
Django Admin in Production Mode doesn't load the admin page after login
I am having some issues with my production mode. In this case, my login page in admin is not redirecting to the admin page after a successful login. I get the server response as: 200. [pid: 58|app: 0|req: 2/3] 172.17.0.1 () {46 vars in 976 bytes} [Wed Jun 22 14:07:32 2022] POST /admin/login/?next=/admin/ => generated 2425 bytes in 40 msecs (HTTP/1.0 200) 12 headers in 623 bytes (1 switches on core 0) But, it stays in the same login page. And, also shows a message: " Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive. " Well... Already tried to understand if my superuser wasn't being created with hashed passwords. But, it is. I made a "python manage.py changepassword" to be sure. I don't have any clue left to troubleshoot this. Just to inform, I am using UWSGI and NGINX. -
While installing the xhtmlpdf in python I am facing the issue with insatlling reportlab package
pip install xhtml2pdf I got the error below: PS D:\pace_at\PACE-AT-NewTech> docker exec pace_at pip install xhtml2pdf Collecting xhtml2pdf Using cached xhtml2pdf-0.2.8-py3-none-any.whl (256 kB) Collecting arabic-reshaper>=2.1.0 Downloading arabic_reshaper-2.1.3-py3-none-any.whl (20 kB) Collecting Pillow>=8.1.1 Using cached Pillow-9.1.1-cp38-cp38-musllinux_1_1_x86_64.whl (3.2 MB) Collecting PyPDF3>=1.0.5 Downloading PyPDF3-1.0.6.tar.gz (294 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 294.8/294.8 kB 1.9 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting python-bidi>=0.4.2 Using cached python_bidi-0.4.2-py2.py3-none-any.whl (30 kB) Collecting reportlab>=3.5.53 Using cached reportlab-3.6.10.tar.gz (4.5 MB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] ##### setup-python-3.8.8-linux-x86_64: ================================================ ##### setup-python-3.8.8-linux-x86_64: Attempting build of _rl_accel ##### setup-python-3.8.8-linux-x86_64: extensions from 'src/rl_addons/rl_accel' ##### setup-python-3.8.8-linux-x86_64: ================================================ ##### setup-python-3.8.8-linux-x86_64: =================================================== ##### setup-python-3.8.8-linux-x86_64: Attempting build of _renderPM ##### setup-python-3.8.8-linux-x86_64: extensions from 'src/rl_addons/renderPM' ##### setup-python-3.8.8-linux-x86_64: =================================================== ##### setup-python-3.8.8-linux-x86_64: will use package libart 2.3.21 !!!!! cannot find ft2build.h [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. -
Python Django can't get static files to work
I'm working on a pyhton django project and now I'm trying to add some style to it with a styles.css file but I just can't get it to work. My project is named commerce and my app is called auctions and I have the static file under commerce/auctions/static/auctions/styles.css My settings.py file include INSTALLED_APPS = [ 'auctions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' My auctions/urls.py from django.urls import path from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ path("", views.index, name="index"), ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() My styles.css file h1 { color: red; } Then in my template file, I have this {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Auctions{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'auctions/styles.css' %}"> </head> <body> <h1>Auctions</h1> </body> </html> It feels like I'm missing something obvious. -
Can It be possible to make an ofline first app with flutter and python?
I am learning app developement. I want to build an ofline-first app. I know how to build apps in flutter so I want to use that technology. But the problem is I want to use python as a backend. But as far as I know it always takes a running server to use python as a backend and the backend code stays separate from the main app which means if an user installs the app he will only get the frontend not the backend. So in this case I cant make an ofline-first app with python. So is there any way to attach all my backend code inside my app and the code will use only the user's device as a localhost and not a cloud server so that I can make the app as an ofline-first app. Please someone give me a solution. For your kind information I use django for python backend -
SQL DAYOFYEAR equivalent in Django
I need DAYOFYEAR of SQL equivalent in Django. I can use ExtractDay for day in month. But I found no day_of_year. Station.objects.all().annotate(day=ExtractDay('measured_date')) -
A count of ForeignKey
I have class Team, which means a group of users. And the relation with User is One-to-Many. class Team(models.Model): member = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) But Team may consist of 2 and N members. I think to write manually is not our way, because it depends on count of people which is always variable. class Team(models.Model): member1 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) member2 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) member3 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) How can I do it more elegant and rational? I mean to connect count variable and ForeignKeys associating with users. -
How to use Reverse Relations in Model Django
Thanks for helping till now, i am facing an issue in Model using Django. Here i am Trying to create 4 Foriegn Keys of DeviceException Table in DeviceControlPolicy Table for individual Device. This DeviceException table will consist 4 Type of Device Exceptions and i am creating individual Columns as foriegn key in the DeviceControlPolicy Table for the each Device, just to make it easy. [if any suggestion please let me know how can i use this] and how can i solve this error DeviceControlPolicy.py from django.db import models from .src.models.Vendor import Vendor from .src.models.DeviceException import DeviceException class DeviceControlPolicy(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) usb_storage_device = models.CharField(max_length=10, default="allow") usb_storage_except = models.ForeignKey(DeviceException, on_delete=models.CASCADE) cd_dvd = models.CharField(max_length=10, default="allow") portable = models.CharField(max_length=10, default="allow") portable_except = models.ForeignKey(DeviceException, on_delete=models.CASCADE) wifi = models.CharField(max_length=10, default="allow") bluetooth = models.CharField(max_length=10, default="allow") webcam = models.CharField(max_length=10, default="allow") webcam_except = models.ForeignKey(DeviceException, on_delete=models.CASCADE) serial_port = models.CharField(max_length=10, default="allow") serial_port_except = models.ForeignKey(DeviceException, on_delete=models.CASCADE) usb_port = models.CharField(max_length=10, default="allow") local_printer = models.CharField(max_length=10, default="allow") network_share = models.CharField(max_length=10, default="allow") card_reader = models.CharField(max_length=10, default="allow") unknown_device = models.CharField(max_length=10, default="allow") def __str__(self): return self.name DeviceException.py from django.db import models from .src.models.Vendor import Vendor from .src.models.DeviceClassification import DeviceClassification class DeviceException(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE) id = …