Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
new ERORR TemplateDoesNotExist at index.html in Django python 3
I am new to Django and when I run the project I get an error Unfortunately, previous questions did not solve my problem. TemplateDoesNotExist at / blog/index.html This is my folder structure: country/ urls.py wsgi.py settings.py blog/ migrations/ templates/ blog/ index.html admin.py models.py tests.py urls.py views.py manage.py urls blog : from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.index, name='index'), ] views blog from django.shortcuts import render def index(request): return render(request,'blog/index.html') settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, //snip }, ] INSTALLED_APPS = [ 'blog', //snip ] -
how to insert arabic characters in database?
I'm a Django beginner student that doesn't have much experiences with database since my country uses Arabic characters , I tried to add some Arabic words in my database instead of Eng., but even when I was typing it in shell (sqlite3) it showed it as ??? how can I insert a word likeمرد into database . also if database doesn't show it correctly why when I add a comment through site in Arabic letters it works perfect? -
Django, using oracledb error msg that I need Oracle 19
I am confused since the documentation for oracledb clearly states that everything past 12.1 should work fine. Could someone please explain to me where I went wrong? The error was created when I tried to create migrations. The document I am referencing is: oracledb docs Here is the error: django.db.utils.NotSupportedError: Oracle 19 or later is required (found 12.2.0.1.0). And here is my databases string in my settings.py: from pathlib import Path import sys import oracledb oracledb.version = "8.3.0" sys.modules["cx_Oracle"] = oracledb #the above line was added because of error (django.core.exceptions.ImproperlyConfigured: Error #loading cx_Oracle module: No module named 'cx_Oracle') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': ( '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server123)(PORT=1521))' '(CONNECT_DATA=(SERVICE_NAME=server.domain.com)))' ), 'USER': 'user123', 'PASSWORD': 'password', 'OPTIONS': { 'threaded': True, }, } } -
Django with Stripe webhooks not working with Stripe CLI, but Postman works localhost
I'm trying to implement webhooks in Django with Stripe, but I'm facing an issue where the webhook is not getting triggered after a successful purchase using the Stripe CLI. However, the webhook works perfectly fine when tested using Postman. I've tried multiple libraries and packages, including downloading repositories for webhooks integrated with Django and Stripe, but the problem still persists. I've double-checked all the URLs and made sure that every step has been taken correctly. I'm not including any code here as I've tried many different approaches and downloaded git repos just to test the webhooks, but the problem remains the same. I'm using Windows 11 with VSCode, Stripe CLI, Django Rest Framework, and I've even tried turning off the firewalls, but to no avail. On the other hand, when I tested the Stripe CLI with a NodeJS app, the webhook fired as it should. Can anyone help me troubleshoot this issue and make the webhook work with Django and Stripe CLI? -
getting data from django.core.handlers.wsgi.WSGIRequest
I am writing a Middleware to log all requests to my server. I want the Middleware to exclude sensitive data such as email or password. I have a code doing something like this: class APILogMiddleware: ... def __call__(self, request): request_data = str(getattr(request, 'body', '')) response = self.get_response(request) try: request_data = json.loads(ast.literal_eval(request_data)) request_data.pop('password', None) request_data.pop('email', None) except: pass logger.info({ 'request_data': request_data, }) ... But, when I run a post request with the following sensitive data it does not get excluded from request_data: requests.post('some_url/', data={'email':'John.Doe@gmail.com','password': '1234'}) I was trying to pass this problem, and I found out that type(request) is <class 'django.core.handlers.wsgi.WSGIRequest'>, and when I print request.body I get a `<class 'bytes'> looking like this: b'email=John.Doe%John.Doe&password=1234' Well, that wasn't useful for me. I was trying to get the data in a different way from the _post attribute and it works: json.loads(json.dumps(getattr(request, '_post', ''))) But that would only work for POST method requests, as for a PUT method request I DID get a nicely JSON formatted data under request.body. I am trying to find out a way to do the same thing for all kinds of requests. -
Logging requested URLs visited by users
I have a django app up and running. This app is e learning portal. I want to know which course is accessed the most. I also want to know if students have accessed certain pages after certain date/time. I was thinking to log URLs accessed along with who accessed them and date time. After googling, I found different sources suggesting following possible solutions: Write django middleware as suggested here. Instead of writing custom middleware from scratch, I can use django-request library which also seem to implement the functionality as middleware. Use django.server logging extension. ref But I am not able to figure it out how can I use this to log every request to database. Q1. Can someone point me in correct direction? Some have recommended to log inside web server instead of django. Q2. Is it possible to log from nginx to database along with user id who has requested the URL? Q3. Which among above is best solution? -
How to return object from django with react?
How to send id of object with React to django and return data of the object? -
Django | Automatic creation of objects in the model
I have two models 'CardsDesk' and 'Card'. Example: class CardsDesk(models.Model): name = models.CharField(max_length=255, verbose_name='Название колоды', blank=True, null=True) image = models.ImageField(upload_to='media/',verbose_name='Картинка колоды') class Card(models.Model): CHOICES = [ ('Мечи', ( ('Swords_1', 'Туз мечей'), ('Swords_2', 'Двойка мечей'), ('Swords_3', 'Тройка мечей'), ('Swords_4', 'Четверка мечей'), ('Swords_5', 'Пятерка мечей'), ('Swords_6', 'Шестерка мечей'), ('Swords_7', 'Семерка мечей'), ('Swords_8', 'Восьмерка мечей'), ('Swords_9', 'Девятка мечей'), ('Swords_10', 'Десятка мечей'), ('Swords_11', 'Паж мечей'), ('Swords_12', 'Рыцарь мечей'), ('Swords_13', 'Королева мечей'), ('Swords_14', 'Король мечей'), ) ), ............ I need that when I create a Model of type "CardDeck" Automatically create 78 objects with automatically selected categories. Any ideas? I tried the for loop, I tried the def save create(). So far I have absolutely no idea how to implement it. -
Django - form action url not redirecting with GET parameters
In my web page I have 3 forms where none, one or all of the form inputs can appear as parameters in the url. The forms return values for: sorting items choosing a metric for items page number I use sessions to save all of these parameters, which stops them being overwritten by each other, and then I join them into a url parameter string which is then passed into the templates context. The problem is when using <form action="{% url watchlist %}{{url_parameter_string}}"> only the parameter from its corresponding form is returned in the url, and does not return all of the parameters stored inside url_parameter_string. views.py - watchlist view if "url_params" in request.session: for k, v in request.GET.items(): request.session["url_params"][k] = v else: request.session["url_params"] = {} request.session.modified = True url_param_string = "?" + "".join([f"{k}={v}&" for k, v in request.session["url_params"].items()])[:-1] context["url_param_string"] = url_param_string url_param_string: ?graph-metric=max_price&sort-field=total_quantity-asc&page=1&view=items html <form action="{% url view %}{{url_param_string}}" method="GET"> <label for="graph-data-form">Graph Data</label> <select onchange="this.form.submit()" name="graph-metric"> {% for graph_option in graph_options %} <option value="{{graph_option.value}}">{{graph_option.text}}</option> {% endfor %} </select> </form> when the form is submitted url .../portfolio/?graph-metric=max_price All of the other parameters are lost. -
Django FileField throws attribute error when storing ContentFile
I create a ContentFile instance from a string passed to it and try to save it to the model like this: class SampleModel(models.Model): upload = models.FileField( _("Skan"), storage=settings.FILE_STORAGE, upload_to=SewageCompanyConsts.generate_file_path ) file = ContentFile('sample content', name='file.txt') instance = SampleModel(upload=file) instance.save() But when saving it throws AttributeError: 'str' object has no attribute 'generate_filename' which is weird, because FileField should handle ContentFile instance. What am I doing wrong? -
How to get static map with multipolygon as an Image in python
I am looking for way (maybe through an external API) to represent many polygons in an static map. The idea is giving the coordinates to that service,and that service or API must give an static map asn a png image with those polygons. Just like this: How to get that static map with multi polygon as an Image in python? I am using django but any way to do it with python will do. The service must be FREE -
How to replicate what django-allauth does when it creates a user, or how to programmatically submit a form in django?
I am trying to import a bunch of users from an old database into a new system, and I am running into problems when I just create users and add their email addresses. Apparently allauth does some hidden magic behind the scenes that I'm having trouble figuring out, because when one of these users logs in, I get an error from the email template Invalid block tag on line 298: 'user_display'. Did you forget to register or load this tag? This doesn't happen when a user that is registered via a form, which subclasses allauth.account.forms.SignupForm logs in. I thought that maybe I could just send the data through the form, but it requires a request to save, so I either need to figure out all the things that the SignupForm does when it creates a new user, or I need to figure out how to manually create the user using the form, which means I have to supply a request, or at least a fake request. I would appreciate any help here. -
DB constraints vs. clean() method in Django
After creating a clean() method to avoid overlapping date ranges in an admin form, I added an ExclusionContraint to ensure integrity at the DB level, too: class DateRangeFunc(models.Func): function = 'daterange' output_field = DateRangeField() class Occupancy(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE) number_of = models.IntegerField() begin = models.DateField() end = models.DateField(default=datetime.date(9999,12,31)) class Meta: constraints = [ ExclusionConstraint( name="exclude_overlapping_occupancies", expressions=( ( DateRangeFunc( "begin", "end", RangeBoundary(inclusive_lower=True, inclusive_upper=True) ), RangeOperators.OVERLAPS, ), ("unit", RangeOperators.EQUAL), ), ), ] This constraint works as expected, but it seems to precede clean(), because any overlap raises an IntegrityError for the admin form. I would have expected that clean() is called first. I have two questions (related, but not identical to this question): Is there any way to change the order of evaluation (clean() → ExclusionConstraint)? Which method (save()?) would I need to override to catch the IntegrityError raised by the constraint? [Django 4.1.5/Python 3.11.1/PostgreSQL 14.6] -
How to Update value of a Model with another Model's value in Django
class Trade(models.Model): pips = models.FloatField(default=0) direction = models.CharField(max_length=30) new_balance = FloatField(default=0.0) ... class Summary(models.Model): winning_trades = models.IntegerField(default=0) account_balance = FloatField(default=0.0) ... When a user post a request he/she will populate the Trade model, this will update the summary model and send back to the user new summary data. How can I do this in an elegant way? -
Why I cannot call my function (order_detail)in django admin file?
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'orders.admin.OrderAdmin'>: (admin.E108) The value of 'list_display[10]' refers to 'order_detail', which is not a callable, an attribute of 'OrderAdmin', or an attribute or method on 'orders.Order'. System check identified 1 issue (0 silenced). my django admin.py def order_detail(obj): return '<a href="{}">View</a>'.format(reverse('orders:admin_order_detail', args=[obj.id])) order_detail.allow_tags = True # @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'email', 'address', 'postal_code', 'city', 'paid', 'created', 'updated', 'order_detail'] list_filter = ['paid', 'created', 'updated'] inlines = [OrderItemInline] actions = [export_to_csv] admin.site.register(Order, OrderAdmin) -
Error - POST /dsahboard/api/investigator HTTP/1.1 400 160 - Django REST API error
I am trying to incorporate DataTables Editor into a Django REST API. While I am able to get the datatable to display, the create button will not work and returns "POST /dashboard/api/investigator/ HTTP/1.1" 400 160 I've setup the editor according to the documentation but the API still won't seem to accept it. The 400 status code indicates it is a bad request, but what does the 160 mean? Can anyone provide input if I setup the datatable wrong? urls.py from django.urls import path, include from . import views from rest_framework import routers from .views import StudyList, StudyDetail, InvestigatorView app_name = 'dashboard' router = routers.DefaultRouter() router.register('study', views.StudyView) router.register('investigator', views.InvestigatorView) router.register('lead', views.LeadView) router.register('institution', views.InstitutionView) router.register('site', views.SiteView) investigator_list = InvestigatorView.as_view({ 'get': 'list', 'post': 'create' }) investigator_detail = InvestigatorView.as_view({ 'get': 'retrieve', 'PUT': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) urlpatterns = [ path('', views.datatables, name='datatable'), path('investigator/', views.datatables_investigator, name='datatables_investigator'), path('api/', include(router.urls)), path('api/investigator/', investigator_list, name='InvestigatorList'), path('api/investigator/<int:pk>', investigator_detail, name='InvestigatorDetail'), path('api/study/', StudyList.as_view(), name='StudyList'), path('api/study/<int:pk>/', StudyDetail.as_view(), name='StudyDetail') ] datatables_investigator.html {% extends 'base_datatables_editor.html' %} {% block content %} <h1 style="text-align: center; padding-top: 1em; padding-bottom: 1em;">Investigators</h1> <div class="row"> <div class="col-sm-12"> <table id="InvestigatorDataTable" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Institution</th> </tr> </thead> … -
integrity-error django :violates not-null constraint
I build a social media application where all actions are concluded in the same count. However with the like button i get an error even if the code looks exactly the same as the dislike version. The error is: IntegrityError at /like-post null value in column "num_interactions_total" of relation "core_likepost" violates not-null constraint DETAIL: Failing row contains (98, a4aaa95b-a3a5-49a6-8f63-de768bfa0786, 2023-02-02 18:01:13.121023+00, , 1, null, 7). but the num_interactions_total count is already deleted and does not exist in the model or views.py anymore. I've also deleted the migrations. I'm using the postgresql database. I´m a little confused, why it gives me an error only with this button and not with all the others... How do I avoid the null error? Here are the models and views from like and dislike: def like_pdf(instance, filename): ext = filename.split('.')[-1] filename = 'post{}.{}'.format(instance.interactions_total, ext) return os.path.join('uploads', filename) class LikePost(models.Model): post_id = models.CharField(max_length=500) created_at = models.DateTimeField(default=datetime.now) num_likes_total = models.IntegerField(default=0) interactions_total = models.IntegerField(default=0) pdf_like = models.FileField(upload_to=like_pdf, default=None, null=True) def __str__(self): return self.post_id def dislike_pdf(instance, filename): ext = filename.split('.')[-1] filename = 'post{}.{}'.format(instance.interactions_total, ext) return os.path.join('uploads', filename) class DislikePost(models.Model): post_id = models.CharField(max_length=500) created_at = models.DateTimeField(default=datetime.now) num_dislikes_total = models.IntegerField(default=0) interactions_total = models.IntegerField(default=0) pdf_dislike = models.FileField(upload_to=dislike_pdf, default=None, null=True) def __str__(self): return … -
nginx django static cannot fully serve my files(403 permission denied)
I've been dealing with nginx for about 1 week. I have 4 services that I set up with docker, django postgresql fastapi and nginx, but nginx does not serve django's static files. I'm facing 403 error. I tried the solutions of all similar error fields, but it doesn't work (file permission granting file path control) below I am sharing the files I use please help. docker-compose.yml: django_gunicorn: build: . command: gunicorn sunucu.wsgi:application --bind 0.0.0.0:7800 --workers 3 volumes: - ./static:/root/Kodlar/kodlar/static env_file: - .env environment: - DATABASE_URL="**" ports: - "7800" depends_on: - db nginx: build: ./nginx volumes: - ./static:/root/Kodlar/kodlar/static ports: - "80:80" depends_on: - django_gunicorn volumes: static_files: Django Docker File: FROM python:3.8-slim-buster WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . RUN python manage.py migrate --no-input RUN python manage.py collectstatic --no-input CMD ["gunicorn", "server.wsgi:application", "--bind", "0.0.0.0:7800","--workers","3"] Django Settings py: STATIC_URL = '/static/' STATIC_ROOT = '/root/Kodlar/kodlar/static/' Nginx Docker File: FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf Nginx Conf File: upstream django { server django_gunicorn:7800; } server { listen 80; server_name mydomain.com; error_page 404 /404.html; location = /404.html { root /root/Kodlar/kodlar/templates; internal; } if ($host != 'mydomain.com') { return 404; } location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header … -
How Reverse Proxy Django to a subdomain
I'm trying to use Nginx to reverse proxy some applications to different subdomain, the problem is when I try to do this with a Django application it doesn't work well, I get the message that the path does not exist or 404 Page not found. this is a pice of my docker-compose.yaml version: "3.9" services: ww4api: build: . hostname: ww4api command: gunicorn --bind 0.0.0.0:8000 authApi.wsgi --workers=4 depends_on: - db - orion restart: always container_name: ww4api environment: - WW4API_ALLOWED_HOSTS=ww4,ww4api,localhost ports: - 8000:8000 volumes: - .:/app pgadmin: container_name: pgadmin image: dpage/pgadmin4 hostname: pgadmin restart: always depends_on: - timescale environment: - PGADMIN_LISTEN_PORT=5050 nginx: hostname: nginx build: settings/nginx restart: always ports: - 80:80 - 434:434 tty: true volumes: - ./data-models/context:/srv/ww4/context - ./syncthingFolder/Sync:/srv/ww4/projects - ./:/srv/ww4 networks: - default and this is part of my nginx.config worker_processes auto; events { worker_connections 1024; } http { include /etc/nginx/mime.types; server_tokens off; upstream ww4api { server ww4api:8000; } upstream mintaka { server mintaka:8080; } server { listen 80; root /srv/ww4; index index.html; keepalive_timeout 1s; keepalive_requests 5000; location / { try_files $uri $uri/ =404; } location /pgadmin4/ { resolver 127.0.0.11 ipv6=off; proxy_pass http://pgadmin:5050/; proxy_set_header X-Script-Name /pgadmin4; proxy_set_header X-Scheme $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; … -
Django "AND" query: Reverse ForeignKey or ManyToMany giving an unexpected result
I found a different result on an "AND" query depending if it was a reverse of forward query. In a FORWARD query you can do this: Model.objects.filter(x=1) & Model.objects.filter(y=2) Model.objects.filter(x=1, y=2) Model.objects.filter(Q(x=1) & Q(y=2)) All give the same result: a QuerySet that satisfies both conditions (x=1 and y=2). But If I have a REVERSE FOREIGNKEY or MANY TO MANY “AND” query something different happens. This is what I did and expect. I have these models: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() authors = models.ManyToManyField(Author) And let's say I have this data: Headline Pub Date Year Authors Blog Pop 1 2023 Juan Pop Pop 2 2023 Emma Pop Pop 3 2010 Juan, Walmer Pop Other 2023 John Beatles I want to make an “AND” query to get the authors that satisfy both the headline that contains the word “Pop” and Pub Date Year equal to 2023. Expected result: Juan and Emma. Headline Pub Date Year Authors Blog Pop 1 2023 Juan Pop Pop 2 2023 Emma Pop We can use the following methods: Multiple Arguments …