Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
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.