Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using JQuery triggers Uncaught ReferenceError: $ is not defined
I use JQuery in my django project quite often, and it hasn't been a problem so far. Even in my current project, I use it on multiple pages. But on one page, I get this error in the console: Uncaught ReferenceError: $ is not defined This is my JQuery Code: $(document).ready(function(){ console.log("hello") }) This is what I imported in my base.html: <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> Like I said I used JQuery a lot in this project so and it worked fine so far. I also did extend Base.html properly. What could be the problem? -
Docker is taking wrong settings file when creating image
I have Django application where my settings are placed in folder named settings. Inside this folder I have init.py, base.py, deployment.py and production.py. My wsgi.py looks like this: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp_settings.settings.production") application = get_wsgi_application() Problem Every time I create image Docker is taking settings from development.py instead of production.py. I tried to change my setting using this command: set DJANGO_SETTINGS_MODULE=myapp_settings.settings.production It works fine when using conda/venv and I am able to switch to production mode however when creating Docker image it does not take into consideration production.py file at all. Question Is there anything else I should be aware of that causes issues like this and how can I fix it? -
Django - Annotating, Filtering and Sorting on a none to many relationships doesn't work
I am working on a table that display a list of orders with the option to filter and to sort depending either to direct attribute of the order or indirectly to attribute of related models. The two models in question are Order and Block. An Order can have none too many Blocks associated to it and Block always have one unique order. class Order(CustomBaseModel): date_of_order = models.DateField(default=timezone.now, verbose_name="Date of order" ... class Block(CustomBaseModel): ... order = models.ForeignKey(Order, on_delete=models.CASCADE) ... To be able to filter orders with or without block, I annotate my queryset using the following: order_queryset = Order.objects.all().annotate( is_material_available=Case( When(block__isnull=False, then=Value(True)), default=Value(False), output_field=BooleanField() ), ) and then use the filter option on the new annotation: is_material_available = self.data["is_material_available"] if is_material_available == "True": order_queryset = order_queryset.filter(is_material_available=True) elif is_material_available == "False": order_queryset = order_queryset.filter(is_material_available=False) Using this method result in those behaviors: is_material_available=="True": Only fetch orders which have an orders, which is great, but completly disrupts the pagination. Let's say the number of order per page is 8, it will create page with only one order, or more. Also some orders are present in different pages. is_material_available=="False": Fetch orders with and without blocks associated to it, but the pagination works fine. I … -
Duplicate Media(CSS, JS) load when using class inheritance in django components
I am using django-components. Common parts are inherited from parent classes and child classes are registered as components. It is written as follows components.py from django_components import component class Parent(component.Component): def get_context_data(self, data): return { "data": data, } @component.register("aaa") class ChildA(Parent): template_name = "/aaa.html" class Media: css = ["css/my.css", "css/test/aaa.css"] js = "js/common.js" @component.register("bbb") class ChildB(Parent): template_name = "/bbb.html" class Media: css = ["css/my.css", "css/test/bbb.css"] js = "js/common.js" When I call the aaa component in a template, I want to call only the Media (css, js) associated with the ChildA class. xxx.html {% component "aaa" data=""%} However, when we check the expanded HTML, even the Media of ChildB is called as shown below. Expanded final HTML <script src="js/common.js" ></script> <script src="js/common.js" ></script> <link href="css/my.css" media="all" rel="stylesheet"> <link href="css/test/aaa.css" media="all" rel="stylesheet"> <link href="css/my.css" media="all" rel="stylesheet"> <link href="css/test/bbb.css" media="all" rel="stylesheet"> What should I do to avoid calling Media of a component of another class that has the same parent? We have already confirmed that common.js is called only once when ChildB js is specified empty. @component.register("bbb") class ChildB(Parent): template_name = "/bbb.html" class Media: css = ["css/my.css", "css/test/bbb.css"] js = "" -
How to disable the Authorize Button in DRF-Spectacular Swagger Django
Im working on drf-spectacular . My Question is how to desable Authorize Button in drf-spectacular. enter image description hereIs there any settings? "APPEND_COMPONENTS": { "securitySchemes": {"ApiKeyAuth": None} } By using above setting I'm getting error -
Store dynamic choice field form from api call to be able to pass the verification in post request
I'm working on an app that can display the events coming from a google calendar. To be able to do this, the user need to fill a form with the start date, end date, timezone and select a calendar. I'm new to Django and it's ok to make a form with date, text, checkbox but regarding the choice field, it fail because the values are not present in the choice list. Select a valid choice. johndoe@gmail.com is not one of the available choices. This is normal because the values will change according to the user. For that I'm calling the google calendar api before showing the page at GET request. I tried to add it to the form but of course, it doesn't stay while the post method is called. Is there a way to store the value without using the session or database? How do you manage dynamic choice field that isn't coming from database? Here is my code: form.py from django import forms class events_filters(forms.Form): start = forms.DateField(label='Start date') end = forms.DateField(label='End date') calendar = forms.ChoiceField(label='Select calendar') timezone = forms.BooleanField(label="Show timezone") view.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from googleapiclient.discovery import build from google.oauth2.credentials import Credentials … -
pytest-django: allow test to update database
I have a lot of little "tests" I use manually, that is, I run them on demand. Some of them I want to alter the database. I have for a long time used pytest for these. (situation is caching production data in dev environment for some specific testing and debugging) I have been convinced to add pytest-django, which has some great features. It has hijacked my ad-hoc tests; immediately, they can't access or update the database. Database access and allowing updates is documented and I was quickly able to half solve it: enable database access, update the database during the test. But all my changes are backed out. My solution to do that may be bad, well obviously it only half works. I have added this file: conftest.py in what seems to be the correct place (same directory as the tests). with contents: import pytest from django.conf import settings pytest_plugins = [ "tests.fixtures.environments", "tests.fixtures.initial_data", ] @pytest.fixture(scope="session") def django_db_setup(): settings.DATABASES["default"] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'django_api_sync', 'PASSWORD': 'devpassword', 'NAME': 'django_api_sync', 'HOST': 'db', 'PORT': 5432, } settings.DATABASES["dear_analytics"] ={ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'django_api_sync', 'PASSWORD': 'devpassword', 'NAME': 'dear_analytics', 'HOST': 'db', 'PORT': 5432, } @pytest.fixture def db_no_rollback(request, django_db_blocker): django_db_blocker.unblock() request.addfinalizer(django_db_blocker.restore) and then I decorate my … -
AttributeError: Got AttributeError when attempting to get a value for field `comments` on serializer `Post`
**In my blog app when i used to retrive all the posts I got this error. ** AttributeError: Got AttributeError when attempting to get a value for field comments on serializer Post. The serializer field might be named incorrectly and not match any attribute or key on the Post instance. Original exception text was: 'Post' object has no attribute 'comments'. I attached my code below. Help me how to get rid out of this. models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User #Abstract Start class TimeStamp(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Selection(TimeStamp): name = models.CharField(max_length=100) class Meta: abstract = True ordering = ['name'] #Abstract End class Post(Selection): # name = title author = models.ForeignKey(User,on_delete=models.CASCADE) body = models.TextField(_("content")) slug = models.SlugField(_("slug")) likes = models.IntegerField(_("likes"),default=0) def __str__(self): return self.name class Comment(TimeStamp): user = models.ForeignKey(User,on_delete=models.CASCADE) content = models.TextField(_("comments")) likes = models.IntegerField(_("likes"),default=0) post = models.ForeignKey(Post,on_delete=models.CASCADE) def __str__(self): return self.content serializers.py from django.contrib.auth.models import User from rest_framework import serializers from . import models class UserSr(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class Comment(serializers.ModelSerializer): user = UserSr() class Meta: model = models.Comment exclude = ['created_at','updated_at'] class Post(serializers.ModelSerializer): author … -
Django + nginx + gunicorn error while IMAGE PROCESSING [ upstream prematurely closed connection while reading response header from upstream ]
I am using Django, and I believe it is not an issue from Django side. Simply upload an image (~500kb) using a Model Form, and using OpenCV just convert it into the grayscale (plus many more if this works). I have configured using nginx and gunicorn and all functionalities works except file uploading and editing. ERROR: upstream prematurely closed connection while reading response header from upstream, client: 174...194, server: .com, request: "POST / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: ".com", referrer: "http://****.com/" Configuration----------------------- /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=shubham Group=www-data WorkingDirectory=/home/shubham/editor/src ExecStart=/home/shubham/editor/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --timeout 600 \ --bind unix:/run/gunicorn.sock \ src.wsgi:application Restart=always RestartSec=3 [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; client_max_body_size 10000M; proxy_connect_timeout 300s; proxy_read_timeout 300s; client_body_buffer_size 10000M; proxy_max_temp_file_size 10000M; send_timeout 300s; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # … -
How to edit api and add changes in django
I'm sending api like: [ { "id": 1, "name": "Burger", "name_ru": "Burger", "name_en": "Burger", "img": null, "parent_category": 1 }, { "id": 3, "name": "Pizza", "name_ru": "Pizza", "name_en": "Pizza", "img": null, "parent_category": 1 } ] how can edit this api? I want to send parent_category with id and name, not just id. My views.py: class TestList(APIView): def get(self, request, pk, format=None): cc = Child_Category.objects.filter(parent_category_id = pk) serializer = ChildCategorySerializer(cc, many=True) return Response(serializer.data) My models.py: class Parent_Category(models.Model): name = models.CharField(max_length=255) name_ru = models.CharField(max_length=255) name_en = models.CharField(max_length=255) img = models.ImageField(blank=True, null=True) def __str__(self): return self.name_en class Meta: verbose_name_plural = 'Parent Categories' class Child_Category(models.Model): name = models.CharField(max_length=255) name_ru = models.CharField(max_length=255) name_en = models.CharField(max_length=255) parent_category = models.ForeignKey(Parent_Category, on_delete=models.CASCADE) img = models.ImageField(blank=True, null=True) def __str__(self): return self.name_en class Meta: verbose_name_plural = 'Child Categories' -
{{minMaxPrice.price__min}}-{{minMaxPrice.price__max}}
Learning Django and now creating price filter. When min and max price is statick, all good, when chenging filter to dinamic, nothin working. Static range from 0 to 1000 working: filter.html {% load static %} <script type="text/javascript" src="{% static 'product-filter.js' %}"></script> <h3 class="mb-4 border-bottom pb-1">Фильтры</h3> <!-- Price Filter --> <div class="card mb-4"> <h6 class="card-header">Цена</h6> <div class="list-group list-group-flush"> <li class="list-group-item"> <input type="range" id="rangeInput" min="0" max="1000" oninput="maxPrice.value=this.value" /> <p>{{minMaxPrice.price__min}}-{{minMaxPrice.price__max}} </p> </li> <li class="list-group-item"> Максимальная цена: <input type="number" onkeyup="rangeInput.value=this.value" id="maxPrice" min="0" max="1000" /> </li> </div> </div> <!-- Filter 1 --> <div class="card mb-4"> <h6 class="card-header">Категории</h6> <div class="list-group list-group-flush"> {% for cat in cats %} <li class="list-group-item"> <input class="filter-checkbox" data-filter="category" value="{{cat.category__id}}" type="checkbox" />&nbsp; {{cat.category__title}} </li> {% endfor %} </div> </div> template_context.py from .models import Product from django.db.models import Min, Max from django.db.models import FloatField def get_filters(request): cats = Product.objects.distinct().values('category__title', 'category__id') minMaxPrice = Product.objects.aggregate(Min('price', output_field=FloatField()), Max('price', output_field=FloatField())) data = { 'cats': cats, 'minMaxPrice': minMaxPrice, } return data` It's showing filter from 0 to 1000 and showing title range from my prices. Static range from 0 to 1000 Dinamic range not working: filter.html {% load static %} <script type="text/javascript" src="{% static 'product-filter.js' %}"></script> <h3 class="mb-4 border-bottom pb-1">Фильтры</h3> <!-- Price Filter --> <div class="card mb-4"> <h6 class="card-header">Цена</h6> … -
VueJS - How can I check if the user id was changed in local storage so I can check if the token is valid
I have Django back end and a Vue front end. People are able to log in. The user id and token is fetched from the back end and stored in localstorage after successful login. This id is then used in my Vue store so the user can get all the data associated with his account. While logged in you can access all the functionality and see the content associated with user (let's say ID = 1). Authorization with the back end happens through the token being sent in the request headers by the front end. Is this correct? But the back end (Django) does not check that the token being sent in the header belongs to a specific user, every time a requests happens am I right or wrong? Because after logging in I can use every end point that requires authentication and I get the data fine. If I delete the token then obviously that stops from happening. If I change the ID in local storage then I can browse the data of another user because according to Django the token is still valid, because from my observation the token in the request headers is not checked against a … -
Django - What's the difference between "exclude", "__ne", and "~Q"?
In the Django model querySet, I learned three ways to filter 'is not equal'. 1. exclude Model.objects.exclude(a='abc') 2. __ne Model.objects.filter(a__ne='abc') 3. ~Q Model.objects.filter(~Q(a='abc')) Are the above cases mean the same thing? -
Adding checkbox in Django table
I want to create a checkbox table in Django that I can click and confirm. After which, the data will be posted into javascript to be sent to a python function. I have tried different methods but can't seem to work. <doctor.html> {%extends "doctor.html" %} {% block emr %}active{% endblock %} {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <div class="department-table"> <el-table :data="list" stripe style="width: 100%"> <el-table-column prop="id" label="Index" width="180"> </el-table-column> <input type="checkbox"> <el-table-column prop="name" label="Department" width="180"> </el-table-column> <el-table-column prop="registration_fee" label="Registration Fee"> </el-table-column> <el-table-column prop="doctor_num" label="Staff Count"> </el-table-column> </el-table> </div> <div class="filter-container"> <div class="filter-item"> <el-button @click="onAddMedicine">Add</el-button> </div> </div> </div> {% endverbatim %} <script> new Vue({ el: '#app2', data() { return { list: [] } }, mounted() { this.getDepartmentList() }, methods: { getDepartmentList() { // Obtain department list axios.post(ToDJ('departmentList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, // Success notification NotifySuc(str) { this.$message({ message: str, type: 'success' }) }, // Error notification NotifyFail(str) { this.$message({ message: str, type: 'warning' }) } } }) </script> {% endblock %} Output that I obtain: I am new to web development. Hope that someone can assist. Thank you! -
Can Django STATIC_ROOT point to path on another server?
I am using Django 4.0.1 in my project, and right prior to deploying my site, I am faced with the issue of handling my static files. Due to the limit of my server, I have decided to instead serve these static files via CDN. I have already configured my STATIC_URL option in settings.py: STATIC_URL = 'assets/' I am aware that in the Django documentation, they say that this url refers to the static files located in STATIC_ROOT. Of course, normally the latter is an absolute path on your server where the collectstatic command collects the static files and put them there, but I am wondering if I can configure this STATIC_ROOT to point a path which is not on my server. To be precise, I want to know whether I can point STATIC_ROOT to my CDN storage. In that way I can still use STATIC_URL to refer to my static assets, while being able to serve them via CDN. -
Django on apache: Could not find platform dependent libreries <exe_prefix>
I'm trying to deploy a django app in an Apache Server (Wamp) using a virtual environtment, but getting that error. Everything is going well, the problem seems to be happen in the wsgi.py file. The wsgi.py never start the venv so this never start the app. Here is my httpd-vhost.conf: ServerName my.app.name ServerAdmin myadminname@localhost.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIPassAuthorization On Alias /static C:/wamp/apache2/htdocs/<myappname>/frontend/build/static/ <Directory "C:/wamp/apache2/htdocs/<myappname>/frontend/build/static/"> Allow from all Require all granted </Directory> <Directory "C:/wamp/apache2/htdocs/<myappname>/<mysetting's django folder>"> <Files wsgi.py> Allow from all Require all granted </Files> </Directory> #WSGIDaemonProcess <my.app.group> python-path="C:/wamp/apache2/htdocs/<app.name>/env/Lib/site-packages" #WSGIProcessGroup <my.app.group> WSGIScriptAlias / "C:/wamp/apache2/htdocs/<app.name>/<settings folder>/wsgi.py" </VirtualHost> Here is my wsgi.py file: import os import sys # Add the virtual environment path to the system path sys.path.append('C:/wamp/apache2/htdocs/<app.name>/env/Lib/site-packages') # activate_this = 'C:/wamp/apache2/htdocs/<app.name>/env/Scripts/activate_this.py' # execfile(activate_this, dict(__file__=activate_this)) # exec(open(activate_this).read(),dict(__file__=activate_this)) # Activate the virtual environment activate_env = 'C:/wamp/apache2/htdocs/<app.name>/env/Scripts/python' exec(open(activate_env, 'rb').read(), {'__file__': activate_env}) # Set the DJANGO_SETTINGS_MODULE environment variable # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings' # Import the Django application from the Django project from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In the wsgi.py file there are two ways I found for activate the venv. The venv don't have the activate_this.py file but there was an answer I found answer-here that say you simply copying … -
Ajax file download sets filename to random string of characters
I am trying to download a file using ajax. The download works correctly, however, the downloaded filename is set to a random string of characters. I don't think this is relevant since the backend is working, but I'm using django js/html: <script> function downloadFile(){ var filename = 'data.txt'; $.ajax({ url: 'downloadFile', data: {'filename': filename}, success: function(blob, status, xhr){ var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') != -1){ var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]){ filename = matches[1].replace(/['"]/g,''); } } var bd = []; bd.push(blob); var typename = "application/" + filename; var downloadURL = window.URL.createObjectURL(new Blob(bd, {type: typename})); var a = document.createElement("a"); a.href = downloadURL; document.body.append(a); a.click() } }); } </script> ... <button id="downloadFile" type="button" onclick="downloadFile()"><i class="fa fa-download"></i></button> ... django views.py: import pathlib import os def downloadFile(request): fname = request.GET.get('filename') fpath = os.path.join(<local_filesystem_path>, fname) # code to generate file here if pathlib.Path(fpath).exists(): file_download = open(fpath, 'rb') response = HttpResponse(file_download, content_type='application/{}'.format(fname)) response['Content-Disposition'] = 'attachment; filename="{}"'.format(fname) return response and urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('downloadFile', views.downloadFile, name='downloadFile') ] When I click the download button, everything works correctly except that my file has been renamed to … -
Name attribute of input field identical modelform
I am trying to loop through a Model PendingRequest and check the every request instance of a user and approve or decline the users request for each instance.I am using a ModelForm to render my form however, the part that gives issue is that the radio button to click on whether to approve or decline do not share the same input name attribue here is my template <form method="post"> {% csrf_token %} <table> <thead> <tr> <th>Book Title</th> <th>Status</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ book.book.title }}</td> <td> <input type="radio" name="{{ book.id }}" value="approved"> Approve <input type="radio" name="{{ book.id }}" value="not_approved"> Decline </td> </tr> {% endfor %} </tbody> </table> <button type="submit">Update</button> </form> so what i want to achieve is to replace <input type="radio" name="{{ book.id }}" value="approved"> and <input type="radio" name="{{ book.id }}" value="not_approved"> with this below such that when it is rendered, every loop will have same the name attribute but different values <form method="post"> {% csrf_token %} <table> <thead> <tr> <th>Book Title</th> <th>Status</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ book.book.title }}</td> <td> {% for choice in form.approved %} {{choice.tag}} {% endfor %} {% for choice in form.not_approved %} {{choice.tag}} … -
Single Update and Delete API for two models connected with a OneToOne relationship in Django Rest Framework
I've looked extensively on here and probably exhausted all the answers and still haven't found a solution to my particular problem, which is to make an API that update/delete from both models, and I am getting the following error: The .update()method does not support writable nested fields by default. Write an explicit.update()method for serializeruser_profile.serializers.UserSerializer, or set read_only=True on nested serializer fields. In this particular instance this happens when I try to update a field from the user_profile model I have separated my Django project into several apps/folders with each model being in its own folder. I have a user app and a user_profile app each with their own models. the user model is basically an AbstractUser sitting in its own app the user_profile model is as follows: class UserProfile(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='userprofile') location = models.CharField(blank=True, max_length=30) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) The serializers are as follows: `class UserProfileCrudSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('location', 'created_time', 'updated_time') class UserSerializer(serializers.ModelSerializer): profile = UserProfileCrudSerializer(source='userprofile', many=False) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'profile') def update(self, instance, validated_data): userprofile_serializer = self.fields['profile'] userprofile_instance = instance.userprofile userprofile_data = validated_data.pop('userprofile', {}) userprofile_serializer.update(userprofile_instance, userprofile_data) instance = super().update(instance, validated_data) return … -
Angular error with json API with python anywhere- has been blocked by CORS
i want to access an api with angular. the api is hosted by pythonanywhere. When accessing the API I get the following error: Access to fetch at 'https://www.pythonanywhere.com/api/v0/user/myusername/cpu/?format=json' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. data-analysis.component.ts:26 ERROR HttpErrorResponse {headers: HttpHeaders, status: 504, statusText: 'Gateway Timeout', url: 'https://www.pythonanywhere.com/api/v0/user/StevoEs/cpu/?format=json', ok: false, …} python-anywhere.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class PythonAnywhereService { private host = 'www.pythonanywhere.com'; private username = 'myUsername'; private token = 'myToken'; constructor(private http: HttpClient) {} getCpuData(): Observable<any> { const headers = new HttpHeaders({ 'Authorization': `Token ${this.token}` }); return this.http.get<any>( `https://${this.host}/api/v0/user/${this.username}/cpu/?format=json`, { headers } ); } } data-analyse.component.ts import { Component, OnInit } from '@angular/core'; import { PythonAnywhereService } from '../../services/python-anywhere.service'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Component({ selector: 'app-data-analyse', template: ` <div class="card text-center bg-dark"> <div class="card-header"> Server CPU auslastung! </div> <div class="card-body"> <div *ngIf="cpuData"> {{ cpuData }} </div> … -
channels and Django not working, TypeError: WSGIHandler.__call__() takes 3 positional arguments but 4 were given
When I run my server it runs channels ASGI/Daphne System check identified no issues (0 silenced). February 02, 2023 - 15:37:13 Django version 4.1.6, using settings 'CheckingSystem.settings' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. When I open my sever this error 500 Internal Server Error appears TypeError: WSGIHandler.__call__() takes 3 positional arguments but 4 were given -
Django loads static CSS files but won't load JS files
I have been struggling with this for a couple of hours now. I have tried every option I could find so far on SO, but couldn't find any solution to my problem. For some reason Django (version 4.1.6 in VS code) will load the css files, but not the javascript file. The css styling works, is adjustable (I can make changes to the css file and the website-style changes) and is visible in inspect element -> sources. snippet of sources The js file that I have made however is not. The script it's suppose to run on a button click, and works when the js script is placed within the html itself, but returns undefined when used as an external js file. I have tried collectstatic, STATICFILES_DIRS, clearing my cache, moving the js file to different folders, used every different path I could think of (blog/js or static/blog/js or static/js or js for example in my script src) and even reinstalled django. When I use findstatic the js file is found. I have simplified the example as much as possible below. Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Views.py class Archive(generic.ListView): queryset = Blog.objects.order_by('-pub_date') template_name = 'blog/archive.html' Urls.py urlpatterns … -
graphs not updating in Heroku deployed Django app
I recently deployed a Django app on Heroku and it was working as intended, basically the user types in a string which fetches data from an API and then that data is used to generate graphs, which are saved in the static folder and are then loaded to the HTML, but recently it stopped working as intended. <div> <img src="{% static 'app-name/graph_one.svg' %}" id="graph_one" class="img-fluid" alt="Graph One"/> </div> Normal use case is that each new search by the user would make the program generate new graphs which would replace the old, and serve the newly replaced ones to the user. Now, when I type in new searches I can see the data is updated but the graphs are not. It looks like the program is still generating new graphs as intended, but when I check the HTML I get this oddity. graph_one.656fabce7bb8.svg So for some reason the app is now serving these files with added strings, while the new/updated files are in the background. When I look into the deployed folder I see all my graph files are duplicated, one set with these odd strings and one set without (which is what I intended). Actually, when I try to directly … -
Turning mapbox-gl-draw into a Django form field
I have seen Mapbox used in Django forms for recording points on a map. The example I have used is the mapbox-location-field widget: https://pypi.org/project/django-mapbox-location-field/ However, I haven't seen any use of Mapbox for recording polygon information. In my search for a solution I have come across the Mapbox-GL-Js documentation a lot. But, being inexperienced with JS, I don't know how to implement this into my Django app as a form field. The end goal is to have a form comprised of a polygon input field and a few drop down fields which get POSTed to a PostgreSQL database. Is it possible to turn mapbox-gl-draw into a form field that sits alongside other form inputs in a Django app? -
Django VS NodeJS Chatbot App with a reactJS front end
I am looking to select a stack for a project to build a chatbot application where the front end is ReactJS. On the back end I will have requirements to utilize a python library called LANGchain and I may on the longer term require integration with IoT datasets. Would it be better to utilize nodeJS or Django on the backend for an application like this? I am currently reviewing Django and this seems like an obvious choice given the project requirements but I have a concern for speed and scaling with Django. I also am curious on the thoughts when it comes to databases for chatbots. I will be looking to capture and record both sides of the chats to use for training and was thinking SQL or SQLlite would be fine but not sure on the advantage to sticking with a NOSQL database in this application and if there are any benefits. Anyone with some insight?