Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a queryset to refer to all inheriting models that have a separate but the same column?
I would like to catch all products by genre with a single query. Products inherit from Product class but have separate but same column. Is there any reasonable way to do this? models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Disco', 'Disco'), ('Electronic music', 'Electronic music'), ('Rap', 'Rap'), ('Reggae', 'Reggae'), ('Rock', 'Rock'), ('Pop', 'Pop'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Book(Product): GENRE_CHOICES = ( ('Biography', 'Biography'), ('Criminal', 'Criminal'), ('Fantasy', 'Fantasy'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Sci-Fi', 'Sci-Fi'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Film(Product): GENRE_CHOICES = ( ('Adventure', 'Adventure'), ('Animated', 'Animated'), ('Comedy', 'Comedy'), ('Horror', 'Horror'), ('Thriller', 'Thriller'), ('Romance', 'Romance'), ) director = models.CharField(max_length=100, null=False, blank=False) duration = models.IntegerField(null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) The query would work like this products = Product.objects.filter(genre="Disco") -
i have a logistic regression model connected with my django app. So in my model i have a column for example ST_Slope which has 3 string values
i have made some dummy datas. But my problem is, how will a user select for example, when they select flat, how will the model know that flat was selected and it must be assigned as 1 ,and the rest must be 0 am expecting that when a user selects flat on a drop down, the model must know what input the user had -
Blocking Datatables initial table loading display with a loading gif
I have a Django template html page that includes a form for users to upload a data file in JSON format. This data file is then processed, and the data is sent to my PostgreSQL database. The page displays a DataTables table populated by data from the database and three D3 charts. Currently, when I upload a file, I can see the datatable in its raw form for several seconds before the table is fully created. As the table is large, it obscures my D3 chart's initial animations. Ideally, I would like the initial datatable creation to be obscured by a 'loading.gif'. When the datatable creation is complete, I want the user to see the fully formed datatable, and only then do I want the D3 charts to be created/rendered on the page. I have included a loading.gif in my static folder, which correctly displays after file upload. However, after several seconds, the loading.gif disappears, and then, as before, I can briefly see the data in its raw form before the full datatable displays. I am unsure how to completely obscure the datatable creation (with the loading.gif) until the table is fully formed. Here is my DataTables script (below). As … -
Encode error in linux web server and ascii' codec can't encode characters in position 61-62: ordinal not in range(128)
After uploading the Django site to hosting, one of the pages gets a header error. The reason is already found, it is because of different encodings on the servers and when using the function: def view_locale(request): loc_info = "getlocale: " + str(locale.getlocale()) + \ "<br/>getdefaultlocale(): " + str(locale.getdefaultlocale()) + \ "<br/>fs_encoding: " + str(sys.getfilesystemencoding()) + \ "<br/>sys default encoding: " + str(sys.getdefaultencoding()) "<br/>sys default encoding: " + str(sys.getdefaultencoding()) return HttpResponse(loc_info) I get results On the local server: getlocale: ('Russian_Russia', '1252') getdefaultlocale(): ('ru_RU', 'cp1252') fs_encoding: utf-8 sys default encoding: utf-8 And at the time of the hosting: getlocale: (None, None) getdefaultlocale(): (None, None) fs_encoding: ascii sys default encoding: utf-8 And after checking the documentation of the libraries, I can say that ascii table with which the error occurs is used only here. More about the error: UnicodeEncodeError at /input/СТ Б 80x80x2_3600_ОЦ.pdf/extrainf 'ascii' codec can't encode characters in position 61-62: ordinal not in range(128) Unicode error hint The string that could not be encoded/decoded was: l/Pl/СТ Б 80 The error is due to Cyrillic lowercase characters not being included in the ascii. Codewise it occurs when you can't read the name in a function like: 'СТ Б 80x80x2_3600_ОЦ'. def file_assembling(self, input_file, mark_file): … -
Static files being served from the Django app instead of Nginx
My website serves the static files from the Django app instead of the Nginx staticfiles folder but I can't figure out why. My Django app static is on the (Linode) server at: /var/www/DjangoApp/myapp/static/myapp The server static folder is at: /var/www/html/staticfiles/myapp Here's my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/var/www/html/staticfiles/' Here's my urls.py: from django.contrib import admin from django.urls import path,include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')), ] urlpatterns += staticfiles_urlpatterns() Here's my config file at /etc/nginx/sites-enabled/default: server { server_name helpmesaythis.com; location / { proxy_pass http://172.105.76.53:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location /static/ { root /var/www/html/staticfiles; } listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot listen 443 ssl http2; # managed by Certbot ssl_certificate /etc/letsencrypt/live/helpmesaythis.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/helpmesaythis.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = helpmesaythis.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name helpmesaythis.com; return 404; # managed by Certbot } I have restarted/reloaded Nginx and I have been using collectstatic without success. I have also tried the following changes to the default file: location /static { root /var/www/html/staticfiles; } location … -
django timezone dst change should not be observed for Asia/Tehran after 2023
Since 2023 Tehran observes standard Time all year and DST is no longer in use. Python datetime still uses DST for this zone. for example: timezone.localtime(timezone.now()) returns datetime.datetime(2023, 3, 27, 17, 34, 6, 13634, tzinfo=<DstTzInfo 'Asia/Tehran' +0430+4:30:00 DST>) but it should not consider DST and it should observer standard +3:30 time. does anyone know how to change the DST consideration for Django a specific zone? I have tried to use UTC timezone for my project and manually considering the +3:30 offset but I would like to user Asia/Tehran zone. -
No signatures found matching the expected signature for payload | Django - Webhooks - Stripe
I am using stripe and I am trying to connect webhooks to my local computer using django here is the code I am using to receive Stripe webhooks requet that tell me whether the Payment was secced or not: @csrf_exempt def StripeWebhookView(request): CHECKOUT_SESSION_COMPLETED = "checkout.session.completed" # Listen for success payment payload = request.body sig_header = request.META["HTTP_STRIPE_SIGNATURE"] endpoint_secret=settings.STRIPE_WEBHOOK_SECRET try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: print(e) return HttpResponse(status=400) except SignatureVerificationError as e: print(e) return HttpResponse(status=400) if event["type"] == CHECKOUT_SESSION_COMPLETED: print(event) what happens is : charge succeeded than Stripe try to send Request with the dat about the purchase but get error 400 enter image description here so I check out and found that I need to : "Make sure you're using the webhook signing secret which matches the Webhook Endpoint delivering the Event, which you can find in the Dashboard after selecting a specific Webhook Endpoint" (text So i double chekc my "webhook signing secret key" and even wrote it directly in my app: enter image description here the problem is gone and the request from Stripe is received by my computer ! To make sure I didn;t make any mistake configuring env.STRIPE_WEBHOOK_SECRET : I double … -
Django get_fields() call __str__ when returning ForeignKeyField Value
I want to be able to display every field with its respective label and value in an . I currently use the DetailView but when it comes to ForeignKeyFields the template renders the id of the related object. Is it possible to call the str method of the related model and display that value instead of its pk ? I already searched for that question but i seem to be the only person who needs this functionality :D -
Surround with tags option not showing for code fragments in PyCharm
I'm trying to surround a django template code fragment similar to the below with tags. {{ my_var }} or {% for i in my_list %} ... {% endfor %} When I press the key combination ⌥ ⌘ T on macOS, the surround with <tag></tag> option shows only if the selected fragment consists of other tags. It doesn't work for code fragments: -
How to customize django-filter DateTimeFromToRangeFilter
I have django-filter class with DateTimeFromToRangeFilter And im looking for way to custom that in my template like split form.work_date on 2 sides or this is not possible? filters.py class PresenceDateFilter(django_filters.FilterSet): work_date = DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'type': 'date', 'class': 'form-control'}, )) class Meta: model = PresenceDetailInfo fields = ('presence_info__counter_presence', 'work_date', ) template.html {% render_field form.work_date %} -
How to create new div when reach end of view port?
I have a for that shows images in the vertical direction, but when you get to the end of the page it keeps showing to the right so it is cut and to see the other images you have to use the horizontal scroll. template.html <div class="vertical-image"> {% for image in list %} <div class="image"> {{image}} </div> {% endfor %} </div> Result: But I would like that when it reaches the end of the view port it creates another <div class="vertical-image"> and continues showing the content below the previous div as in the following example: Does anyone know how I can do this? -
How to send HTTP-request to django inside a docker-compose network?
Background I have a project with a frontend- and a backend-service and am trying to access the django server via HTTP-request. My docker-compose looks like this: services: backend: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "9005:8000" networks: - test-network frontend: image: my-latest-image depends_on: - backend ports: - "9001:80" networks: - test-network networks: test-network: Issue I am able to successfully execute ping backend from inside the frontend-container, but if I execute curl backend:8000 I get the following message from django: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'backend:8000'. You may need to add 'backend' to ALLOWED_HOSTS. What I tried Other people who got this message pointed out to include something like ALLOWED_HOSTS = ['backend'] in their 'settings.py'-file (as the error message pointed out). I already did that and am still getting the exact same error message. Is there something I still need to configure or should configure differently to communicate with the 'backend'-service from inside the 'frontend'-service? -
Messes up class names in Django admin panel
[enter image description here][1]Im practicing Django and Ive noticed something weird. For now Im working only in the admin page. Im defining a class model "Meetings", however in the admin panel its defined with double s at the end, why that happens ? models.py: class Meetings(models.Model): title = models.CharField(max_length=200) date = models.DateField() start_time = models.IntegerField(default=time(9)) # Hours duration = models.IntegerField(default=1) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return f"{self.title} at {self.start_time} on {self.date}" admin.py from .models import Meetings admin.site.register(Meetings)``` Im expecting it to have the same name as my definition of it, aka "Meetings" [1]: https://i.stack.imgur.com/auLrj.png -
Sanitizing user input for writing into Python config file
How do you sanitize user input so that it's safe for writing into a Python file? Basically, there is a form where user submit some data, which I need to write into a Python file, userconfig.py. For example, a form field asking for title will be declared as value for TITLE in the file as below - TITLE = "some input by user" I write it simply as myfp.write(f"TITLE = {form.cleaned_data.get('user_title')}\n") The title here can allow a mix of ASCII & non-ASCII characters but still want it to be safe from any code injection. I just want to ensure that this user input is not malicious or has any malicious code in it. -
Django local server issue with env file
I'm using an env file to store passwords for database access. I created a python(db_config.py) file to use them: import os from constant.Const import Const mysql_db_config = Const() mysql_db_config.HOST = os.getenv('DB_MYSQL_HOST') mysql_db_config.USER_NAME = os.getenv('DB_MYSQL_USER') mysql_db_config.PASSWORD = os.getenv('DB_MYSQL_PASS') mysql_db_config.DBNAME = os.getenv('DB_MYSQL_NAME') In the Django seetings.py file I'm importing it and create the database: from project.config.db_config import mysql_db_config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': mysql_db_config.DBNAME, 'USER': mysql_db_config.USER_NAME, 'PASSWORD': mysql_db_config.PASSWORD, 'HOST': mysql_db_config.HOST, 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } } } The problem is that when I'm trying to start the server locally the values are "None" and I can't figure it out what's the reason. -
PyScript - NameError: name 'function' is not defined -- then *.py is load with <py-script src="..."> (DJango)
I have a Python script containing a plot calculation and a function definition: import matplotlib.pyplot as plt import numpy as np from pyscript import Element import datetime x = np.random.randn(1000) y = np.random.randn(1000) fig, ax = plt.subplots() ax.scatter(x, y) display(fig, target="plot") def current_time(): now = datetime.datetime.now() # Get paragraph element by id paragraph = Element("current-time") # Add current time to the paragraph element paragraph.write(now.strftime("%Y-%m-%d %H:%M:%S")) which I want to load into the HTML using DJango expressions combined with the py-script: <py-script src="{% static 'py/script.py' %}"></py-script>. I found that the script is loaded and executed but the function is not recognised by the HTML button. If move the function code directly into the HTML tag, it works. What is going wrong here? Function definition within external py script {% extends "proj/base.html" %} {% load static %} {% block head %} <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css"/> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <py-config type="toml"> packages = ["numpy", "matplotlib"] </py-config> {% endblock head %} {% block content %} <div id="plot"></div> <button py-click="current_time()" id="get-time" class="py-button">Get current time</button> <p id="current-time"></p> {% endblock content %} {% block script %} <py-script src="{% static 'py/script.py' %}"></py-script> {% endblock script %} results to: Function definition within HTML tag {% extends "proj/base.html" %} {% load … -
How to pass parameter to raw sql in Django
I am trying to create a simple ledger using raw SQL query in Django through my view.py. If I add my parameter value direct I get my required results but if I follow the tutorial here I get the error message below. ERROR MESSAGE ProgrammingError at /books/ledger/1005068200/ not enough arguments for format string Request Method: GET Request URL: http://127.0.0.1:8000/books/ledger/1005068200/ Django Version: 4.1.7 Exception Type: ProgrammingError Exception Value: not enough arguments for format string Exception Location: c:\xampp\htdocs\tammgo\app-env\Lib\site-packages\MySQLdb\cursors.py, line 203, in execute.... CODE I HAVE TRIED views.py from django.shortcuts import render from django.core.paginator import Paginator from django.contrib import messages from django.db.models import Q from django.shortcuts import redirect, render, reverse from django.urls import reverse_lazy from django.http import HttpResponse from books.forms import VoucherForm, GlForm, PersonForm, GlgroupForm, AccountForm from . models import Voucher, Gl, Persons, Glgroup, Account from django.views import generic from django.views.generic import ( CreateView, DetailView, View, ) class BookLedgerView(DetailView): model = Voucher template_name = "books/Vourcher_ledger.html" def get(self, request, *args, **kwargs): sql = '''SELECT datecreated, accountnumber, vtype, id, accountnumber, datecreated, debit, credit, @balance:= @balance + debit - credit AS balance FROM (SELECT datecreated, id, accountnumber, vtype, amount, @balance:=0, SUM(CASE WHEN vtype='dr' THEN amount ELSE 0 END) AS debit, SUM(CASE WHEN vtype='cr' THEN amount ELSE … -
How do I properly configure `drf-spectacular` in my Django projects
I simply installed and configured drf-spectacular in my Django project, but when I visit the url http://127.0.0.1:8000/api/v1/schema/, Django throws this error. TypeError at /api/v1/schema/ Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: school>. This is my root urls.py file from django.contrib import admin from django.urls import path, include from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('schools.urls')), path('api/v1/years-terms/', include('years_terms.urls')), path('api/v1/schema/', SpectacularAPIView.as_view(), name='schema'), path('api/v1/schema/redoc/', SpectacularRedocView.as_view(url_name="schema", ), name='redoc'), path('api/v1/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name="schema"), name='swagger-ui'), ] In my settings.py file, I have this SPECTACULAR_SETTINGS = { "TITLE": "School Veil API Project", "DESCRIPTION": "A school management system", "VERSION": "1.0.0", } What could possibly be wrong? -
Whenever I try to execute django-admin command: +FullyQualifiedErrorId: CommandNotFoundException error
Every time when I install something on CMD, for example, Flutter, Python, or Django, I get this problem: This time when I try to execute django-admin startproject pyshop . django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject pyshop . + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException And I already checked everything, such as dictation, such as the installation path I added it to Edit the system environment variables, and I checked the status of the Django installation, and they are all good, with no problems, yet the error appears again, and I watched almost all the educational videos or read almost all the articles, but it didn't work, it's Annoying, isn't it? What is the solution to this problem, please? I already checked everything, such as dictation, such as the installation path I added it to Edit the system environment variables, and I checked the status of the Django installation, and they are all good, with no problems -
how to serve static file in deplyment?
i have a django rest framework project which serve some endpoint.i deploy it on a linux server.But it is dosen't show any static file of django rest framework.In my project hasn't any static file.My nginx config is following server { listen 80; server_name 192.168.31.50; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django JSONField store timetable data and query only open businesses
Hi in my Django backend I need to store business's timetable and I do it through a JSONField like the example below: [ { "times":[ [ "7:00", "9:00" ], [ "", "" ] ], "closed":false }, { "times":[ [ "7:00", "9:00" ], [ "", "" ] ], "closed":false }, { "times":[ [ "7:00", "9:00" ], [ "", "" ] ], "closed":false }, ... ] Then I need to create a query to get all the opened businesses in a corresponding user_time at a day of current_day_index. How can I index the json, for example index = 0 => "Monday", to select the timetable for that specific day and then compare the user_time with the elements in the array "times" and check if the business is open or not? Are there better solutions to achieve this behaviour to store timetable data? Thank you -
I have an error during the session, code 400, message Bad request version ('')
Let's me explain that. Few days ago I installed a django app with docker, I had no problem with that, and later I tried to add a security for settings.py and now I have an error code 400, message Bad request version ('') You're accessing the development server over HTTPS, but it only supports HTTP. and now when I start creating new app I have a same error but I did not add security for new app So my files db.sqlite3 manage.py requirements.txt src venv I am using django 4.0 with psycopg 2.9.3 Next, when I am going to run a server python manage.py runserver I have seen that Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 27, 2023 - 09:17:44 Django version 4.0, using settings 'src.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I log in to the server http://127.0.0.1:8000/ I see on browser this https://localhost:8000/ and a same error code 400 Shoud i delete a docker? … -
I want to generate a form based on the previous form using django and html css javascript
suppose I am filling a form which has two entry: department(comps, extc, etrx, it) and year(fy, sy, ty). based on this form I want to generate a template of credit scheme table form Suppose user filled comps and fy then generate a credit scheme table form for that department and year and if user chooses extc and sy then generate new credit scheme table form. and if user again chooses comps and fy then generate previously generated credit scheme table form. I have one credit scheme table form. I have one form which has department and year as input How should I do this task. -
django (djangorestframework-simplejwt) : How to set up SIGNING_KEY value different for each user
I am using djangorestframework-simplejwt for setting up the jwt token based authentication In my user model i have column jwt_secret = models.UUIDField(editable=False, default=uuid.uuid4) I wanted to use different jwt_secret for each token user. So in future if i want to logoff a user from all places i can change this value In can see djangorestframework-simplejwt has a setting variable called SIGNING_KEY How to mention in the settings that it should use per user based SIGNING_KEY For more clearity -
Wagtail Change Image signal
Its my signal for cropping original images. Its work well in upload, but don't work when i change image in 'wagtail.images.views.images.edit'. /wagtail.hooks.py/ import os from django.db.models.signals import post_save from django.dispatch import receiver from wagtail.images import get_image_model ImageModel = get_image_model() @receiver(post_save, sender=ImageModel) def optimize_image_storage(sender, instance, created=False, **kwargs): if created: croped_image = instance.get_rendition('max-2000x2000|jpegquality-80') croped_file = croped_image.file.path original_file = instance.file.path try: os.rename(croped_file, original_file) except FileExistsError: # windows error os.replace(croped_file, original_file) instance.width = croped_image.width instance.height = croped_image.height instance.file_size = os.path.getsize(original_file) instance.save()