Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() -
Django audio recording issue: receiving Bad Request error
I am really new to Django and also building an application. I am building an audio journaling application with Django. I am trying to make a recorder with Django, and I have receive a bad request error. The code: views.py @login_required def record_audio(request): print("11",request.method) print("1") if request.method == 'POST': print("2") if 'blob' not in request.POST: print(request.POST) print("3") return HttpResponseBadRequest('Missing audio-blob parameter') print("4") now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") print("5") filename = f"{request.user.username}_{now}.wav" print("6") file_path = os.path.join(settings.MEDIA_ROOT, filename) # Save the audio file to the server print("7") with open(file_path, 'wb') as f: f.write(request.POST['blob'].encode()) return HttpResponse(status=204) # Return a 204 No Content response else: print("8") return render(request, 'recording/record.html') record.html {% extends 'base.html' %} {% load static %} {% block content %} <h1>Recorder</h1> <section class="experiment" > <br> <h3> Send Message: Speech to text </h3> <button id="start-recording">Start</button> <button id="pause-recording" disabled>Pause</button> <button id="resume-recording" disabled>Resume</button> <button id="stop-recording" disabled>Stop</button> </section> <section class="experiment"> <div id="audios-container"></div> </section> {% include "chat_script.html" %} <script src="https://cdn.WebRTC-Experiment.com/MediaStreamRecorder.js"></script> <script src="{% static 'js/jquery-1.12.3.js' %}"></script> <!-- <script src="{% static 'js/bootstrap.min.js' %}"></script> --> <!-- <script src="{% static 'js/script.js' %}"></script> --> <!-- <div> <audio id="audio-player" controls></audio> </div> --> {% endblock %} urls.py path('record-audio/',views.record_audio,name="record_audio"), chat_script.html <script> function captureUserMedia(mediaConstraints, successCallback, errorCallback) { navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback); } var mediaConstraints = { audio: true }; document.querySelector('#start-recording').onclick = … -
Django sessions not saving data from form, no error or apparent reason
I have a view with different 'stages' (as I wanted to keep the same URL without resorting to something like AJAX), which takes data from a form, does some processing, and then would save that data to the database. Because I can't forward some data via POST, I wanted to save that data in a session. For some reason, this is not working - at all. I can see the data being extracted from the form, and I can forward that via POST, but attempting to save or retrieve it to a session either results in blank data, or a KeyError. This is the view I am using (very trimmed down, but the error is reproducible) def processpayment(request, *args, **kwargs): if request.method == 'POST': form = paymentDetailsForm(request.POST) amount = request.POST.get('amount', False); stage = request.POST.get('stage', False); if (stage == "checkout"): return render(request, "payment.html", {'form': form, 'amount': amount, 'stage': stage}) if (stage == "complete"): return render(request, "payment.html", {'amount': request.session['amount'], 'stage': stage, 'name': request.session['name']}) if (amount == "custom"): if form.is_valid(): amount = form_data.get('amount') name = form_data.get('name') request.session['amount'] = amount request.session['name'] = name request.session.modified = True return render(request, "payment.html", {'form': form, 'stage': stage, 'amount': amount}) return render(request, "payment.html", {'amount': amount, 'stage': stage}) else: return … -
Django - How to make a relationship in Django that is related to a multiple ManyToManyField model
I am a django beginner. I have two models here that are used in another model as a ManyToManyField : In models.py : class Likelihoods(models.Model): Likelihood = models.CharField(primary_key=True, max_length=255) Param = models.CharField(max_length=255) class Consequences(models.Model): Consequence = models.CharField(primary_key=True, max_length=255) Param = models.CharField(max_length=255) class Inherent_risks(models.Model): Likelihood = models.ManyToManyField(Likelihoods, related_name= 'InherentRisk_Likelihood') Consequence = models.ManyToManyField(Consequences, related_name= 'InherentRisk_Consequence') After this, i added it to another model in order to create a form name Hira. class Hira(models.Model): Activity = models.CharField(max_length=255) Risk_Description = models.TextField(default="***") PBS = models.ManyToManyField(PBS) Physical_control = models.CharField(max_length=255) Administrative_control = models.CharField(max_length=255) Instrumented_control = models.CharField(max_length=255) Inherent_Risk = models.ForeignKey(Inherent_risks, on_delete=models.CASCADE, related_name='Inherent_risk' ) The form.py : class HiraForm(ModelForm): class Meta: model = Hira fields = '__all__' The question : The form i am getting I can't choose both a likelihood and a consequence (not even any data). What am I doing wrong ? -
How to use django oram to implement oracle wm_concat query
In oracle, I can use wm_concat to implement row-to-column conversion, as follows: SELECT * FROM STU_TEST name project Alice Machine Learning Alice Data Science Bob Web Development Bob Mobile Development Carol Data Science Carol Cloud Computing David Artificial Intelligence SELECT NAME,wm_concat(PROJECT) FROM STU_TEST GROUP BY NAME name wm_concat(PROJECT) Alice Machine Learning,Data Science Bob Web Development,Mobile Development Carol Data Science,Cloud Computing David Artificial Intelligence I want to implement this query using django orm, I tried the following, without success. 它返回了错误:cx_Oracle.DatabaseError: ORA-00937: not a single-group group function from django.db.models import CharField, Value from django.db.models.functions import Concat from django.db.models.aggregates import Count from myapp.models import StuTest from django.db.models import Func class GroupConcat(Func): function = 'LISTAGG' template = '%(function)s(%(expressions)s, \',\') WITHIN GROUP (ORDER BY %(expressions)s)' results = StuTest.objects.values('name').annotate(project_concat=GroupConcat('project')).order_by('name') for result in results: print(result['name'], result['project_concat']) How to implement this query? (In the actual environment, group by may not only include the name field, but also other fields)