Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem loading wasm data for SciChart in Django - scichart2d.data = 404
I can only load a blank SciChart surface with a "loading... spinner". Firefox console says: Uncaught Error: Internal Server Error : http://127.0.0.1:8000/charts/scichart/scichart2d.data Django is serving scichart2d.wasm correctly, but not scichart2d.data (which is in the same static dir) My HTML and javascript seem to be working, the Webpack bundle loads and logs to console. I followed the SciChart tutorial here. I don't know where this problem is coming from. Is it Webpack, Django, or SciChart? Here's the Django terminal output: System check identified no issues (0 silenced). February 14, 2024 - 01:14:59 Django version 5.0.2, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [14/Feb/2024 01:15:03] "GET /charts/scichart/ HTTP/1.1" 200 7752 [14/Feb/2024 01:15:03] "GET /static/bundle.js HTTP/1.1" 200 5155989 [14/Feb/2024 01:15:03] "GET /static/js/bootstrap.bundle.min.js.map HTTP/1.1" 304 0 Not Found: /charts/scichart/scichart2d.data [14/Feb/2024 01:15:04] "GET /charts/scichart/scichart2d.data HTTP/1.1" 404 3985 [14/Feb/2024 01:15:04] "GET /static/scichart2d.wasm HTTP/1.1" 304 0 I tried intercepting the request for '/charts/scichart/scichart2d.data' in Django: charts/urls.py from .views import scichart, sciChartData, urlpatterns = [ path("scichart/", scichart, name="scichart"), path('scichart/scichart2d.data', sciChartData, name="sciChartData") ] charts/views.py def sciChartData(request): print(request) dataURL = static('scichart2d.data') return FileResponse(open(dataURL,'rb'), filename='scichart2d.data', as_attachment=True, ) but I couldn't successfully return the .data file to SciChart. The print(request) is <WSGIRequest: GET '/charts/scichart/scichart2d.data'> Python Version … -
Django: Migrating from multiple databases to a single database?
I'm relatively new to Django (and web systems architecture more broadly) and mistakenly thought that building my project with separate databases for user data and core application data was a good idea. I originally created two applications, core and users, with separate router classes: settings.py DATABASES = { "default": { }, USERS_DATABASE: { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": ..., "PASSWORD": ..., "HOST": "127.0.0.1", "PORT": "5000", }, CORE_DATABASE: { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": ..., "PASSWORD": ..., "HOST": "127.0.0.1", "PORT": "5000", }, } routers.py class AuthRouter: route_app_labels = { "auth", "contenttypes", "sessions", "admin", } ... class CoreRouter: route_app_labels = { "core", } ... Knowing now that it's not necessary for our project to use separate core and users databases (and that doing so will give us more problems in the future), I'd like to migrate the users database into the core database and assign the core database to be the default. There are only two users at the moment, so I'm fine with losing the users data and recreating the superuser if need be. However, migrating the users database doesn't seem as straightforward as editing settings.py and creating migrations. Editing the databases settings.py to both point to the core database and … -
how to collect information of this json file through django?
so, I'm creating a django weather app project. My idea is: The user input the name of a city The city need to be in my database If it is, so the weather api will receive the city coordinates and output data I would like to know how do I get parameters of a json file through django. Do I need to do it with the views? create a model? some request? I did this in views: from django.http import HttpResponse import requests from datetime import datetime from zoneinfo import ZoneInfo def weatherdata(request): response = requests.get('api is here').json() context = {'response':response} return render(request,'home.html',context) def citynamesinfo(request): response = request.FILES() #I don't what to do here # input localization # recognize specific coordenates and in models: from django.db import models # Create your models here. class Weather(models.Model): city = models.CharField(max_length=100) temperature = models.DecimalField(max_digits=5,decimal_places=2) condition = models.CharField(max_length=100) precipitation = models.CharField(max_length=100, null=True) humidity = models.DecimalField(max_digits=5,decimal_places=2) considering the json file is like this: [{"geoname_id": "3112344", "name": "R\u00e1fales", "ascii_name": "Rafales", "alternate_names": ["Rafales", "Rafels", "R\u00e1fales", "R\u00e1fels"], "feature_class": "P", "feature_code": "PPLA3", "country_code": "ES", "cou_name_en": "Spain", "country_code_2": null, "admin1_code": "52", "admin2_code": "TE", "admin3_code": "44194", "admin4_code": null, "population": 175, "elevation": null, "dem": 634, "timezone": "Europe/Madrid", "modification_date": "2012-03-04", "label_en": "Spain", "coordinates": … -
Django-Crispy-Forms, different layout for forms of a formset
I have a formset, this formset consists of 12 forms, each form has a different initial, and the forms have crispy helper layouts. However, since each form has its own distinct initials, we can't have a general layout for all of the forms, which mean we can't set the layout for the formset. Is there anyway we can set a different layout for each form in the formset? i've already tried overriding _construct_form of the formset but it appears that it doesn't work. -
Django static files Dokku
I am encountering an issue with Django and Whitenoise where my static files are not being served correctly, resulting in 404 errors and MIME checking errors. I have configured my config/settings.py file with the necessary settings for static files and Whitenoise middleware: INSTALLED_APPS = [ # some apps 'django.contrib.staticfiles', # my apps ] MIDDLEWARE = [ # some middleware 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STORAGES = { "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') However, when I try to access static files such as http://example.com/static/css/style.css and http://example.com/static/js/script.js, I get 404 errors, and the browser console shows MIME type errors: Refused to apply style from 'http://example.com/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to execute script from 'http://example.com/static/js/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. The logs indicate the files are not found: Not Found: /static/css/style.css Not Found: /static/js/script.js -
Abstract model in Django with ForeignKey doesn't inherit as expected
When attempting to execute makemigrations in my Django application, I encounter errors related to circular references. I have defined an abstract class A that inherits from models.Model, and two child classes B and C. However, it seems I am making mistakes with the relationships between these classes. Here is the relevant code: class A(models.Model): class Meta: abstract = True id = models.AutoField(primary_key=True) z = models.ForeignKey(Z, on_delete=models.CASCADE, related_name="relateds") class B(A): algo = models.CharField(max_length=32, default="") class C(A): foo = IntegerField() I am facing the following error: z.B.z: (fields.E305) Reverse query name for 'z.B.z' clashes with reverse query name for 'z.C.z'. Any help or suggestions on resolving this issue would be greatly appreciated! -
Create an app: input data from user and export to csv. Python?
I'm a beginner in development and I'm looking to create a lightweight Python application. The idea is to have a user interface that allows users to input data through some mandatory steps and later export them to a CSV file. For this purpose, I'm considering whether to go for a desktop application using Tkinter or a local web app with Flask or Django. I would appreciate advice on the best choice between these two options, considering simplicity, lightweight nature, and portability. P.S. I've already tried with django, but after a while I started to doubt that it was too "heavy". Thanks! -
Django react integration Trouble when dist is not immediate child of frontend folder which has pages
We are building different pages so each has different folder inside frontend, but when we put the contents of sign up folder in front end folder directly and do npm run build, then removing sign up in path join expression in settings.py, then its working. why is it so? How to fix? file tree settings.py -
CSS won't load in DJango
I have 2 apps that I work with at the moment in my project: Home and header. The home app have the following html code located in project_folder -> home -> templates -> home -> base_home.html {% extends 'header/base_header.html' %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <header> {% block content %} {% endblock %} </header> </body> </html> The header is located in project_folder -> header -> templates -> header -> base_header.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> This is the settings.py: import os from pathlib import Path # Build paths inside the project like … -
Hiding EMAIL_HOST_USER and its password in a Django app
Able to hide EMAIL_HOST_USER and its password in a Django app and successfully deploy it to PythonAnywhere. But when I deploy the same app to Heroku, I will get 'gaierror', but when I went back to a contact page, a successful message was displayed. If secret informations are in settings.py, the submission form will be successful. All environment variables are correctly set on Heroku under the 'Settings' tab. Any help and advise would be appreciated Thank you -
Javascript code to display to pictures in one row
I have a javascript code for website and I need the two pictures array to show in one row. I have tried the css flex but that not how we want them to appear are we able to join two pictures in javascript? slides[slideIndex-1].style.display = "inline-block"; slides[slideIndex].style.display = "inline-block"; I have tried css flex but since they are scrollable items they move all over the place and we only want them at the center. tried adding a parent class to arrange them in column css but didnt work -
Outlook Add-in to parse emails and populate Django Database
I'm trying to find the best way to get some sort of a button in Outlook (add-in) that will perform some functions on my django project - like parsing the email and search for a specific stirngs in it and then, populate my database. I already achieved the population using a BaseCommand but now i want to add a button to the outlook app. Has someone did that? is it possible? tried https://yeoman.io/ -
Fcm-django Message.data must not contain non-string values error
I use fcm-django library def get(self, request, *args, **kwargs): user = request.user devices = FCMDevice.objects.filter(user=user) body_data = { "title": "Title text", "body": "Click to explore more", } extra_data = {"type": "some information", "link": "https://google.com", "badge": str(10)} for device in devices: try: if device.type == "ios": device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data)) else: device.send_message(Message(data={**body_data, **extra_data})) except Exception as e: return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK) IOS could not handle the string, it needs Integer badge value. If I change badge to Int error raised Message.data must not contain non-string values How can I fix this problem. I did not find info in library documentation( -
How to display a pdf in django and not let it download
I have a pdf file uploaded to the site (the Internet library and the pdf file of the book in it), how can I allow viewing this file while only on the site, and prohibit printing or downloading it. I will be grateful for tips or links to articles on how to do this. Everything I found on the Internet is not suitable, because the file can be downloaded and printed. I'm a beginner, so please don't laugh at my question. -
Static file error on Django windows server
I installed my project on Windows server, but it cannot see the static files. I tried many examples on the internet, but I could not solve the problem. please guide me on this Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static/") #STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) python manage.py collectstatic This is the result I get when I do it: You have requested to collect static files at the destination location as specified in your settings: C:\inetpub\vhosts\demo.com.tr\httpdocs\static This will overwrite existing files! Are you sure you want to do this? Type ‘yes’ to continue, or ‘no’ to cancel: yes 0 static files copied to ‘C:\inetpub\vhosts\demo.com.tr\httpdocs\static’, 126 unmodified. -
How to run Celery and Django web app simultaneously on Railway?
I'm trying to deploy a Django web application along with Celery for background task processing on Railway. I've configured my railway.json deployment file as follows: { "$schema": "https://railway.app/railway.schema.json", "build": { "builder": "NIXPACKS" }, "deploy": { "startCommand": "celery -A core worker --loglevel=INFO && python manage.py migrate && python manage.py collectstatic --noinput && gunicorn core.wsgi --timeout 60", "numReplicas": null, "healthcheckPath": null, "healthcheckTimeout": null, "restartPolicyType": "ON_FAILURE", "restartPolicyMaxRetries": 10, "cronSchedule": null } } However, with this configuration, only Celery starts, and the Django web server (gunicorn) doesn't seem to run. How can I adjust my deployment configuration to ensure that both Celery and the Django web app start and run simultaneously? I've tried rearranging the startCommand, placing celery at the end, but it doesn't seem to work. Any guidance or best practices for configuring Celery and Django web app deployments on Railway would be greatly appreciated. Thank you! -
django.db.utils.OperationalError: no such table: django_site while running pytest even though django_site exists
I am using openedx project and I want to run all unit tests. Even though the django_site table exists in my database when I run pytest I get the error: django.db.utils.OperationalError: no such table: django_site The database info is following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': TEST_ROOT / "db" / "cms.db", 'ATOMIC_REQUESTS': True, }, } I am using this command to run the tests: pytest --create-db --ds=lms.envs.test --exitfirst openedx/core/. What can I do to fix this? -
Dynamically add/remove DateFields in Django formset
I have a very specific problem which is related to the package django-bootstrap-datepicker-plus. In my Todo list application I want to have the possibility to have tasks pop up on a number of specific dates. I got my model set up, I got my form including a formset set up, and I even have a JavaScript that handles the dynamic add/remove procedure. The problem that I have is that the cloning process of my DateField somehow messes with the DatePicker divs - see the outcome in the last code block below. # model.py from django.db import models from datetime import time # Create your models here. class Task(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50, default="") description = models.CharField(max_length=500, default="") entry_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) specific_dates = models.ManyToManyField('SpecificDate', blank=True) due_until = models.TimeField(auto_now_add=False, default=time(12, 0)) class SpecificDate(models.Model): todo = models.ForeignKey(Task, on_delete=models.CASCADE) date = models.DateField(auto_now_add=False, blank=True, null=True) class Meta: # ensure each specific date is unique per task unique_together = ('todo', 'date') # forms.py from bootstrap_datepicker_plus.widgets import DatePickerInput, TimePickerInput from django import forms from .models import Task, SpecificDate class TaskForm(forms.ModelForm): class Meta: model = Task fields = [ 'title', 'description', 'due_until', ] widgets = { 'due_until': TimePickerInput(options={'stepping': 5, 'format': 'HH:mm'}), 'description': forms.Textarea({'rows': … -
i'm try to schedule a email by django signal
Geting the errors in qcluster terminal "django_q\cluster.py", line 432, in worker res = f(*task["args"], **task["kwargs"]) TypeError: 'NoneType' object is not callable" from django.db.models.signals import post_save from django.dispatch import receiver from django_q.tasks import schedule from django_q.models import Schedule from django.utils import timezone from django.conf import settings from django.core.mail import send_mail from .models import Lead @receiver(post_save, sender=Lead) def schedule_lead_email(sender, instance, **kwargs): scheduled_time = timezone.now() # Adjust the time delay as needed schedule( send_follow_up_email, instance.email, name=f'Send-lead{instance.name}', schedule_type='O', # 'O' stands for 'Once' next_run=scheduled_time, ) def send_follow_up_email(email): # Send your email using the provided email address send_mail( 'Subject', 'Message', settings.EMAIL_HOST_USER, # Use your sender email [email], fail_silently=False, ) this is the models.py code. from django.db import models class Lead(models.Model): name = models.CharField(max_length=100) email = models.EmailField() phone_number = models.CharField(max_length=20) lead_purpose = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
using keycloak in with legacy system for provide OAuth2
we have legacy Backend which stored users with their password . we need create oAuth2 provider for our bussiness . there is recommendation to use Keycloak for this purpose . but can i import my users with hashed password to Keycloak ? is it good to use this service ? can you provide advice and recommendation ? -
In starting my page templates in django are visible but, then some of pages are not visible and new pages are also not visible
I made pages in django in starting (about us, contact us, blogs, home) and then shop page. After all this my some of previous pages (about us, contact us, blogs) are not visible/displaying, also now if i am creating any new page it also not displaying. Even all the things (views, urls) are configured correctly.[previous page](https://i.stack.imgur.com/8fJJI.png)shop pagenew page {% extends 'base.html' %} {% block content %} {% load static%} <link rel="stylesheet" href="/static/css/contact_us.css"> <section> <div class="section-header"> <h2>Contact Us</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p> </div> <div class="container"> <div class="contact-info"> <div class="contact-info-item"> <div class="contact-info-icon"> <i class="fas fa-home"></i> </div> <div class="contact-info-content"> <h4>Address</h4> <p>Jankpuri South,<br/> New Delhi, India, <br/>55060</p> </div> </div> <div class="contact-info-item"> <div class="contact-info-icon"> <i class="fas fa-phone"></i> </div> <div class="contact-info-content"> <h4>Phone</h4> <p>571-457-2321</p> </div> </div> <div class="contact-info-item"> <div class="contact-info-icon"> <i class="fas fa-envelope"></i> </div> <div class="contact-info-content"> <h4>Email</h4> <p>support@shemade.com</p> </div> </div> </div> <div class="contact-form"> <form action="" id="contact-form"> <h2>Send Message</h2> <div class="input-box"> <input type="text" required="true" name=""> <span>Full Name</span> </div> <div class="input-box"> <input type="email" required="true" name=""> <span>Email</span> </div> <div class="input-box"> <input … -
Python / Django deploy issue on Heroku
I am trying to deploy a Python / Django app for a class project and been told I have to use Heroku, which I don't like at all! Initially when I tried to push to heroku using the cli git push heroku main, i got an error saying 'No default language could be detected for this app.' So I added Python Buildpack within the Heroku dashboard. Now I get an error saying App not compatible with buildpack. I've followed the Heroku django app config installing gunicorn and configured the setting.py here is my file structure and setting.py, can anyone advise why is not pushing to heroku? """ Django settings for recipe_project project. Generated by 'django-admin startproject' using Django 5.0.1. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = … -
Challenge with Ordering Django Signals and Celery Tasks for Group Operations
I'm facing an issue in my Django project where the execution order of Django signals and Celery tasks is causing complications, particularly in managing group operations asynchronously. Specifically, when there's a change in group administrators triggering the update_group_admins signal, the create request task (create_group_async) should ideally be executed before the tasks for adding or removing group members (add_group_admins_async and remove_group_admins_async). However, despite my meticulous planning, the sequence of execution remains incorrect, leading to errors and inconsistencies in the system. To address this issue, I've attempted various approaches to reorder the tasks and signals within my codebase. My expectation was that by ensuring the correct sequence of execution, the create request task (create_group_async) would be processed before the tasks for adding or removing group members (add_group_admins_async and remove_group_admins_async). However, despite my efforts, the execution sequence remains erroneous, and I haven't been able to achieve the desired outcome. -
How to solve logout error when using Django-Jazzmin?
I hope you are doing fine! I have built a django project recently, and while searching for methods to customize the admin panel, I found Django-Jazzmin. It is working and cool and all that, but I have one single problem with it, whenever I try to logout from the admin page, it returns the error 405, a.k.a "method not allowed". I am working with the Django 5.0.2 framework. Did someone find the solution for this problem? I tried to go to "my-virtual_env\Lib\site-packages\jazzmin\templates\admin\base.html" and modify the logout block to : <form method="post" action="{% url 'admin:logout' %}"> {% csrf_token %} <button type="submit" class="dropdown-item"> <i class="fas fa-users mr-2"></i> {% trans 'Log out' %} </button> </form> but it didn't help! -
Django - How to use AJAX within a form
I'm trying to use AJAX for the first time as we have a Django project but a required feature is for one form to behave more like a react app or SPA so I'm trying to use AJAX to add that functionality. I have the following template for the page. It has a form to let the user select from a dropdown what their highest education is and should have a modal appear to let the user input a qualification at a time to be added to the database and displayed on the table. The issue is when the user fills out the modal and clicks submit it seem's to perform just a normal GET request as can be seen below rather than the API request to create qualifications from the modal. AJAX seemingly isn't intercepting the request. GET REQUEST "GET /applications/personal-details/prior-attainment/4/?csrfmiddlewaretoken=s54x6U2BczYThuoYKTryBZwUzdPDuaxmzzubamRRz2Lw4qX1ztjGnAP1XcryPHXP&subject=Maths&qualification_name=Nat+5&date_achieved=2024-02-13&level_grade=A HTTP/1.1" 200 7974 {% extends 'base.html' %} `{% block content %} <div class="container mt-5"> <h2>Prior Attainment and Qualifications</h2> <form id="priorAttainmentForm" method="post" action="{% url 'prior_attainment_view' application_id %}"> {% csrf_token %} <div class="form-group"> <label for="highestQualification">Highest Qualification Level</label> <select class="form-control" id="highestQualification" name="highest_qualification_level"> {% for value, label in form.highest_qualification_level.field.choices %} <option value="{{ value }}" {% if form.highest_qualification_level.value == value %} selected {% …