Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying a Django web application that uses SQL Server
I am getting ready to deploy my Django app, with a SQL Server backend, but I'm not sure where to even start. I've done a lot of research and reading, but I have not found any clear path to follow. Does it have to be hosting with AWS, Azure, or the like? Can it instead be hosted on my Windows Server (on-prem)? -
Apache2 not starting on Debian server after following dev.to guide
I am trying to host my Django website on my Debian 12 server but I am encountering an error even after following the guide on dev.to. The error is that Apache2 is not starting and is showing the following message: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xeu apache2.service" for details. After running systemctl status apache2.service it is showing that without matching section. I have tried the following steps to fix the problem: I have checked that the Apache2 service is not running everytime restarting the server. I have checked that the port 80 is not being used by another process. I have cleared the Apache2 configuration files. I have reinstalled Apache2. However, I am still getting the same error. Can anyone help me to fix this problem? <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) … -
Django with djangorestframework-simplejwt results in POST error 403: Forbidden (CSRF cookie not set.): on /api/token/
i want to set up a simple Django Backend with a rest api. If i'am trying to login with the supplied urls, but everytime i try to login i get a 403 error: CSRF Verficatoin failed. CSRF cookie not set. This are my used apps: Django==4.1.10 # Rest Framework djangorestframework==3.14.0 djangorestframework-api-key==2.3.0 djangorestframework-simplejwt==5.2.2 markdown==3.4.4 # CORS for rest api django-cors-headers==4.2.0 and my settings: ALLOWED_HOSTS='*, localhost' ALLOWED_ORIGINS='http://*, https://*' CSRF_COOKIE_AGE=31449600 CSRF_COOKIE_NAME='csrftoken' CSRF_USE_SESSIONS=False CSRF_TRUSTED_ORIGINS='http://*, https://*' CSRF_COOKIE_HTTPONLY=False CSRF_COOKIE_SECURE=False CSRF_COOKIE_DOMAIN = None CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' CORS_ALLOW_ALL_ORIGINS=False CORS_ALLOWED_ORIGIN_REGEXES='' CORS_ALLOWED_ORIGINS='http://localhost:8888, http://127.0.0.1:8888' the server runs on port 8888 with the command: python3 manage.py runserver 0.0.0.0:8888 The Middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and the Settings for the Rest Framework: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', # 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', # only for testing ], "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", ], } and these urls are in the introduction of the app: path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), and now, if i try following request: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "my_username", "password": "my_password"}' \ http://localhost:8888/api/token/ i get the error code 403, as described … -
Django a problem that chatgpt can not solve :-) i am newbie [closed]
`Django 4.2.3 I have a problen when i try to create a window. First i create a quote then when i want to add a window to the quote, the connection field between class Quote and class Windows is "quot" field. This field is shown to the user at the moment the user want to create a new window At the moment the form is sent to the function function create_window do not enter in the if form.is_valid() so it gives an error "This field is required" <ul class="errorlist"><li>quot<ul class="errorlist"><li>This field is required.</li></ul></li></ul> VIEW.py def create_window(request, quote_id): quote = get_object_or_404(Quote, pk=quote_id) if request.method == 'POST': form = WindowForm(request.POST) print(form.errors) if form.is_valid(): window = form.save(commit=False) window.quot = quote # Assign the related Quote form.cleaned_data['quot'] = quote window.save() return redirect('detail_quote', pk=quote_id) else: form = WindowForm(initial={'quot':quote}) context = {'form':form} return render(request, 'create_window.html', context) create_window.html <!DOCTYPE html> <html> <head> <title>Create New Window</title> </head> <body> <h1>Create New Window</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Create"> </form> </body> </html> MODELS.py class Quote(models.Model): quote_number = models.PositiveBigIntegerField(null=True, blank=True, unique=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) slug= models.SlugField(max_length=100, unique=True) def save(self, *args, **kwargs): if not self.quote_number: self.quote_number = generate_next_quote_number() super(Quote, self).save(*args, **kwargs) def __str__(self): return f"Nro Presupuesto: {self.quote_number}" def … -
pydev debugger: unable to find translation for: (please revise your path mappings)
I have a problem using debugpy with vscode on Windows with the repository on a local server. I have a dockerized django app with the following dockerfile and docker-compose: FROM python:3.6.15-slim-bullseye ARG ENVIRONMENT=master # Python logs to STDOUT ENV PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ TZ=America/Santiago \ DEBIAN_FRONTEND=noninteractive WORKDIR /app COPY requirements.txt . RUN set -x \ && buildDeps=" \ git \ build-essential \ libpq-dev \ libssl-dev \ locales \ gnupg \ wget \ " \ && runDeps=" \ pkg-config \ unzip \ lsb-release \ libcairo2-dev \ libpangocairo-1.0-0 \ " \ && apt-get update \ && apt-get install curl tzdata -y \ && apt-get install -y --no-install-recommends $buildDeps $runDeps \ && ln -fs /usr/share/zoneinfo/${TZ} /etc/localtime \ && dpkg-reconfigure -f noninteractive tzdata \ && locale-gen es_CL.UTF-8 \ && sed -i -e 's/# es_CL.UTF-8 UTF-8/es_CL.UTF-8 UTF-8/' /etc/locale.gen \ && wget http://dev.mysql.com/get/mysql-apt-config_0.8.26-1_all.deb \ && echo 'mysql-apt-config mysql-apt-config/select-product select Ok' | debconf-set-selections \ && dpkg -i mysql-apt-config_0.8.26-1_all.deb \ && rm mysql-apt-config_0.8.26-1_all.deb \ && apt-get update \ && apt-get install -y libmysqlclient-dev \ && pip install -r requirements.txt --no-dependencies \ && apt-get clean \ && apt-get autoremove -y \ && rm -rf /var/lib/apt/lists/* \ && rm -Rf /tmp/* version: "3.8" services: django: image: "django:dev" build: … -
Change the url that search_form hits during search in Django admin changelist page
I have a custom implementation for the changelist page in the Django admin, such that a custom query parameter is provided in the url. For example, it is like this: admin/app_label/model_name/?custom_parameter=value Although I have made the changes I needed to filters and action to work using this url, I have an issue with search. Hitting the search in changelist page, I see that it hits the normal url admin/app_label/model_name/ . This is an issue since I need the custom parameter in the GET request to appropriately handle things in the django admin backend. I have also seen the search_form.html file that renders the search element. Is there a way to define the url that the search will hit, either from the backend or somehow via the javascript of the search_form.html, since I also have the custom_parameter provided in the context of the html page? -
(admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'name', which is not a field of 'store.Category'
I'm making an ecommerce app with Django. The command terminal keeps popping the above error whenever I try to run a command with it. models.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length = 150, db_index = True), slug = models.SlugField(max_length = 150, unique = True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name = 'product', on_delete = models.CASCADE) created_by = models.ForeignKey(User, on_delete = models.CASCADE, related_name= 'product_creator') title = models.CharField(max_length = 150) author = models.CharField(max_length = 150, default = 'admin') description = models.TextField(blank = True) image = models.ImageField(upload_to = 'images/') slug = models.SlugField(max_length = 150) price = models.DecimalField(max_digits = 4, decimal_places = 2) in_stock = models.BooleanField(default = True) is_active = models.BooleanField(default = True) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title admin.py: from django.contrib import admin from .models import Category, Product @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug' : ('name',)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'slug', 'price', 'in_stock', 'created', 'updated'] list_filter = ['in_stock', 'is_active'] list_editable = ['price', 'in_stock'] prepopulated_fields = {'slug' : ('title',)} It's also worth noting that for … -
Django gunicorn nginx 111 connection refused while connecting to upstream
A fresh Django application is running on the Debian server, configured via gunicorn and nginx. After setup i tried to connect to it, but i can reach it only by server ip. The only error i found is in nginx log: 2023/08/10 16:08:48 [error] 19252#19252: *9 connect() failed (111: Connection refused) while connecting to upstream, client: x.xx.xxx.xxx, server: mydomain.ru, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "xxx.xxx.xxx.xxx:80" or sometimes host: "mydomain.ru" my nginx configuration: server { listen 80; server_name mydomain.ru; access_log /var/log/nginx/example.log; location /static/ { root /home/alex/myproject; expires 30d; } location /media/ { root /home/alex/myproject; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } my gunicorn.conf bind = '127.0.0.1:8000' workers = 2 user = 'alex' timeout = 120 mydomain.ru is in django settings ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS, but anyway, when i python3 manage.py runserver django shows some activity only accessing it by server ip. when i stop project with supervisor there are no other servers in netstat -tpln Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:10050 0.0.0.0:* LISTEN 324/zabbix_agentd tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 20083/nginx: master tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 358/sshd tcp … -
Django - try to refresh the page when the basket is empty
I'm sort of new with Django and I ran through an issue. I'm doing a E-commerce project. I'm sending a post request to django basket view and return the function back with HttpResponse in order to change the product details in the basket. The issue is: once the product quantity went from 1 to 0, the page is not displaying an empty basket in the default way. Is that impossible to return a HttpResponseRedirect and JsonResponse at the same time, right? Do you guys have any idea how to do it?Can I do something in the ajax part to refresh the basket page? Here's are the codes: Views.py def basket_delete(request): basket = Basket(request) basketqty = basket.__len__() if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) basketqty = basket.__len__() #calculating the basket quantity baskettotal = basket.get_total_price() response = JsonResponse({'qty':basketqty, 'subtotal':baskettotal}) return response Ajax in the html template <script> $(document).on("click", ".delete-button", function (e) { e.preventDefault(); var prodid = $(this).data("index"); $.ajax({ type: "POST", url: '{% url "basket:basket_delete" %}', data: { productid: $(this).data("index"), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { $('.product-item[data-index="' + prodid + '"]').remove(); if (json.qty == 0) { total = 0 subtotal = 0 } else { total = (parseFloat(json.subtotal) + … -
Uncaught (in promise) TypeError: this.resolveComponent is not a function | Inertia, Django & Vue
I have a Vue page (FormTest.vue): <template> {{ user }} <form @submit.prevent="submit"> <input type="text" v-model="user.first_name" label="First name" /> <input type="text" v-model="user.last_name" label="Last name" /> <button type="submit">Save</button> </form> </template> <script setup lang="ts"> import {User} from '@/types/users'; import {router} from '@inertiajs/vue3'; const props = defineProps<{ user: User; }>(); function submit() { router.post('/form-test', { first_name: props.user.first_name, last_name: props.user.last_name, }); } </script> Then a Django view: def form_test(request): user_instance = get_object_or_404(CustomUser, pk=request.user.id) if request.method == "POST": form_data = dict_to_querydict(json.loads(request.body)) form = CustomUserForm(form_data) if form.is_valid(): user_instance.first_name = form.cleaned_data["first_name"] user_instance.last_name = form.cleaned_data["last_name"] user_instance.save() return render( request, "FormTest", props={"user": CustomUser.objects.get(id=request.user.id)}, ) The update works, it correctly stores the values in the db and on the page I see them change within the {{ user }} as well. Just running into an error in the console upon submission: router.ts:452 Uncaught (in promise) TypeError: this.resolveComponent is not a function at C.setPage (router.ts:452:33) at router.ts:390:21 setPage @ router.ts:452 (anonymous) @ router.ts:390 XMLHttpRequest.send (async) dispatchXhrRequest @ xhr.js:251 xhr @ xhr.js:49 dispatchRequest @ dispatchRequest.js:51 request @ Axios.js:148 wrap @ bind.js:5 visit @ router.ts:342 post @ router.ts:527 submit @ FormTest.vue:20 (anonymous) @ runtime-dom.esm-bundler.js:1328 callWithErrorHandling @ runtime-core.esm-bundler.js:158 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166 invoker @ runtime-dom.esm-bundler.js:278 Show 13 more frames Somewhere within the render function something goes … -
frozen importlib._bootstrap error i can't import that package
[ In the main also have some isue how can i clear the bug .help me this is my first website . -
Having two users....here i want to one user does'nt allow to edit and delete process and another user allows all in django
```Created Website in Django...Here the user can login and use the pages....Here I'm having two users first user can access the whole pages I mean they can View,Edit and Delete operations but another user allows only View only how? Can anyone explain me No,I don't Know how to do. -
NoReverseMatch at / Reverse for 'conference' not found. 'conference' is not a valid view function or pattern name
I'm working on my project and I got stuck on this issue and have no ideas how to solve it. <li class="nav-item"> <a class="nav-link {% if 'conference' in segment %} active {% endif %}" href="{% url 'conference' %}"> <i class="ni ni-collection text-blue"></i> <span class="nav-link-text">Конференц зал</span> I got error here. my views.py from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse @login_required(login_url="/login/") def index(request): context = {'segment': 'conference'} html_template = loader.get_template('conference/conference.html') return HttpResponse(html_template.render(context, request)) @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] if load_template == 'admin': return HttpResponseRedirect(reverse('admin:index')) context['segment'] = load_template html_template = loader.get_template('home/' + load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template('home/page-404.html') return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template('home/page-500.html') return HttpResponse(html_template.render(context, request)) my urls.py of my app from django.urls import path from .views import * urlpatterns = [ path('conference/', index, name='conference'), # Other URL patterns for your app's views... ] All my apps are in apps folder. I have one folder for all templates of apps and inside of that I have templates with … -
unable to access admin panel django
I have changed my views and more specifically the request-mappings to "spring-like request mappings for djang". There for I had to change my urls to work as follows link to Pypi documentation of spring-like request mappings for django. After that change tho, Im unable to access admin panel, even tho I have it registered in my project urls.py. Project urls.py: from myapp.views import UserView from django.contrib import admin urlpatterns = UrlPattern() urlpatterns.register(UserView) urlpatterns += [path('', include('myapp.urls'))] urlpatterns += [path('admin/', admin.site.urls)] Of course I have it imported in my settings, it used to work before that url refactoring I did. I just want to mention that I like this way of work and my question is specifically how do I fix the access to the admin panel, if it is possible ofc. The error Im getting is: The current path, admin/, didn’t match any of these. -
Using the Tnymce Responsive File Manager in Django
How can I use Tnymce File Responsive Manager in Django? I can't use it in any way! I tried writing some code but it didn't work. Please help me! ` Full content {{ new.full_info }} ` <script type="text/javascript"> tinymce.init({ selector: 'textarea#myTextarea', plugins: [ 'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak', 'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'emoticons', 'template', 'help', ], toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | insertfile link image | print preview media fullscreen | ' + 'forecolor backcolor emoticons | help', menu: { favs: { title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons' } }, menubar: 'favs file edit view insert format tools table help ', tinydrive_upload_path: '/upload', // content_css: 'css/content.css', file_picker_callback: function(callback, value, meta) { if (meta.filetype === 'file') { // Fayl tanlash dialogini ochish tinymce.activeEditor.windowManager.openUrl({ url: '/admin/filepicker/', // Fayl tanlash uchun Django view URL title: 'Fayl tanlash', onMessage: function(dialogApi, details) { // Tanlangan faylni fayl tanlash dialogidan olib kelib, callback ga uzatish callback(details.file); dialogApi.close(); } }); } } }); </script> -
drf-yasg : How can we use doc-string of different methods other than standard http method for swagger api documentation
I am using drf-yasg and django-rest-framework. I am having one common parent class which is having all http method defined, which will be inherited in sub-classes where business logic methods will be overided. I want subclass overrided method docstring in swagger api documentation class BaseAPIView(APIView): """ Base API View. """ def get(self, request): """ Base API get method description. """ result = self.process_get() # Call the overridden method return Response(result) def process_get(self): raise NotImplementedError class DerivedAPIView(BaseAPIView): """ Derived API View. """ def process_get(self): """ List all items. """ items = [ {"name": "Item 1", "description": "Description of Item 1", "price": 10.99}, {"name": "Item 2", "description": "Description of Item 2", "price": 20.99} ] return Response(items) Here in swagger document for DerivedAPIView get method i want DerivedAPIView process_get method docstring as api documentation. -
DRF: Redirect unauthenticated users to login form
Is there a way to redirect users who didn't pass through rest_framework.permissions.IsAuthenticated permission to login page? I can achieve it by rewriting dispatch method of my ApiView and adding extra NotAuthenticated exception catcher, but is there a softer way to do this? class IndexView(APIView): permission_classes = [ IsAuthenticated, ] def get(self, request, format=None): ... def dispatch(self, request, *args, **kwargs): self.args = args self.kwargs = kwargs request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except NotAuthenticated: "<---- added by me" return redirect("/login") except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response -
Change city slug on django-cities to only have city name with hyphens
I am using django-cities in my project, and I am stuck at an issue which I can't seem to be able to overcome on my own. I basically need the slug field of the City model to only list the city name, with hyphens if the name has spaces. This is the standard behaviour of the Country model slug. Instead, the City model returns something like [id]-[city]. So the slug for Country is: United-Arab-Emirates But the slug for City is: 292968-Abu-Dhabi I think I've identified where this is generated in django-cities. The BaseCity model has a field slug_contains_id which is set to True, then the slugify method adds it to the slug before the city name: django-cites.models: class BaseCity(Place, SlugModel): slug_contains_id = True name_std = models.CharField(max_length=200, db_index=True, verbose_name="standard name") country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities', on_delete=SET_NULL_OR_CASCADE) region = models.ForeignKey(Region, null=True, blank=True, related_name='cities', on_delete=SET_NULL_OR_CASCADE) subregion = models.ForeignKey(Subregion, null=True, blank=True, related_name='cities', on_delete=SET_NULL_OR_CASCADE) location = PointField() population = models.IntegerField() elevation = models.IntegerField(null=True) kind = models.CharField(max_length=10) # http://www.geonames.org/export/codes.html timezone = models.CharField(max_length=40) class Meta: abstract = True unique_together = (('country', 'region', 'subregion', 'id', 'name'),) verbose_name_plural = "cities" @property def parent(self): return self.region def slugify(self): if self.id: return '{}-{}'.format(self.id, unicode_func(self.name)) return None But what I'm unable to … -
how to add next and prev pages in our single blog post in django
i wanna add next and prev pages in my single blog post and i tried something but dose not work so well and this my url that i made for my site http://127.0.0.1:8000/blog/pid views.py def blog_single(request, pid): post = blog_Post.objects.get(published_date__lte=timezone.now(), status=1, pk=pid) post.counted_views += 1 post.save() context = {'post':post} return render(request, "blog/blog-single.html", context) i try this next_post = blog_Post.objects.filter(id__gt=post.id).order_by('id').first() prev_post = blog_Post.objects.filter(id__lt=post.id).order_by('id').last() but it dose not work -
Django Docker container without database container - best practise?
I am a little bit confused about the database Docker container. I read everywhere that is not good practise to dockerize a database, for example here. But if I search for Django Docker container then I see almost in every Docker Compose file that a Postgres database container is included. For example I have this docker-compose.yml file: version: '3.9' services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - .:/app command: > sh -c "python manage.py migrate && python app/manage.py runserver 192.168.1.65:8000" env_file: - variables.env depends_on: - db db: image: postgres:13-alpine container_name: postgres volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=dzijn - POSTGRES_USER=zijn - POSTGRES_PASSWORD=password volumes: dev-db-data: dev-static-data: It has also a Docker database. Is it better to omit the database container in the Docker Compose file and for example to store the database in a cloud service? Because I am using Microsoft Azure for the hosting. -
General way of iterating over a dictionary containing multiple mpld3 graph images in Django?
I am working on a personal project. One part of this is to display multiple histograms on a webpage. So far, I have been able to get this to work using the following code: views.py: import pandas as pd import matplotlib.pyplot as plt,mpld3 import scipy.stats as stats import numpy as np for column in df.columns: fig=plt.figure() plt.hist(df[column]) histogram=mpld3.fig_to_html(fig) context[f"{column}Histogram"]=[histogram] HTML Code: {% for elem in PregnanciesHistogram %} {{elem|safe}} {% endfor %} {% for elem in GlucoseHistogram %} {{elem|safe}} {% endfor %} {% for elem in BloodPressureHistogram %} {{elem|safe}} {% endfor %} {% for elem in SkinThicknessHistogram %} {{elem|safe}} {% endfor %} {% for elem in InsulinHistogram %} {{elem|safe}} {% endfor %} {% for elem in BMIHistogram %} {{elem|safe}} {% endfor %} {% for elem in DiabetesPedigreeFunctionHistogram %} {{elem|safe}} {% endfor %} {% for elem in AgeHistogram %} {{elem|safe}} {% endfor %} I do see all the histograms on my webpage, but the problem is that all of the HTML code uses hardcoded keys in the dictionary. Is there a general way of writing what I wrote in this HTML code, using a for loop, without hardcoding the keys from the dictionary? I would appreciate it if someone could tell me … -
How to (conditionally) remove SCRIPT_NAME from MEDIA_URL in urls.py
Situation: working in Debug=True mode in Django. I want to serve files from the media root, so I follow the documentation hint: urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And it works perfectly (remember to read the note: MEDIA_URL should be local i.e. media/. Don't put a / in front of it. Important!). I have a media resource called 123456.txt, in the admin interface I get the link: /media/123456.txt. Now I move to Apache (still in debug), but I run this Django site in a subfolder of the server, and everything works fine, thanks to the WSGI variable SCRIPT_NAME which gets prepended to all URIs. So just to be clear, I have https://example.com/subfolder as the root for the Django site and the previous media resource called 123456.txt, in the admin interface I get the link: /subfolder/media/123456.txt. So the link is correct. When I request the resource https://example.com/subfolder/media/123456.txt, Apache recognizes the subfolder and sends to Django a request for media/123456.txt, as expected. The problem is that the url pattern created by the static() helper function now includes the SCRIPT_NAME prefix, so when I click on the resource, I get an exception … -
Django SELECT Query
Hi Iam try to select from mysql using Django my models.py from django.db import models from django.db.models import Q class Series(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) des = models.CharField(max_length=255) img = models.CharField(max_length=255) isseries = models.IntegerField() istrend = models.CharField(max_length=255) background_img = models.CharField(max_length=255) trial_url = models.CharField(max_length=255) imdb_id = models.CharField(max_length=255) rate = models.CharField(max_length=255) date = models.CharField(max_length=255) status = models.IntegerField() isdel = models.IntegerField() section_id = models.IntegerField() poster_img = models.CharField(max_length=255) genres = models.CharField(max_length=255) class Meta: db_table = 'series' my sample Script series = series_db.objects.filter(istrend=1,status=1,isdel=0).order_by('id').values() i want to SELECT all columnt without isdel so i remove isdel from models.py, but when i remove it i cant use isdel to make WHERE isdel = 0 in mysql so i got This Error django.core.exceptions.FieldError: Cannot resolve keyword 'isdel' into field. so how i can use isdel to make a condition without select it LIKE this Example SELECT `series`.`id`, `series`.`title`, `series`.`des`, `series`.`img`, `series`.`isseries`, `series`.`istrend`, `series`.`background_img`, `series`.`trial_url`, `series`.`imdb_id`, `series`.`rate`, `series`.`date`, `series`.`status`, `series`.`section_id`, `series`.`poster_img`, `series`.`genres` FROM `series` WHERE (`series`.`isdel` = 0 AND `series`.`istrend` = '1' AND `series`.`status` = 1) ORDER BY `series`.`id` ASC real Example SELECT `series`.`id`, `series`.`title`, `series`.`des`, `series`.`img`, `series`.`isseries`, `series`.`istrend`, `series`.`background_img`, `series`.`trial_url`, `series`.`imdb_id`, `series`.`rate`, `series`.`date`, `series`.`status`, `series`.`isdel`, `series`.`section_id`, `series`.`poster_img`, `series`.`genres` FROM `series` WHERE (`series`.`isdel` = 0 AND `series`.`istrend` … -
I am trying to install django-jazzmin but I am getting an error
When I try to install django-jazzmin using command pip install django-jazzmin I am getting the error. ERROR: Could not find a version that satisfies the requirement django>=2 (from django-jazzmin) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26, 1.11.27, 1.11.28, 1.11.29) ERROR: No matching distribution found … -
chatterbot: how to utter a default welcome message?
My Chatterbot instance is ready and trained. But it only replies when the user initialize the conversation. I want my chatterbot instance to utter a default message. How can I do that? My chatterbot instance is installed in a "django project".