Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I access my django app on other devices in my environment using some custom domain?
I have a django app which I hosted locally on my system, now since other devices are connected and on the same local network as my django app, they too are able to access the website by typing the ipaddress:port of my django app host device. But I wanted those devices also to access my django app using some domain name, but it's not working. Here is what I tried. Edited the hosts file on windows and added 127.0.0.1 anythingyoulike.com 127.0.0.1 www.anythingyoulike.com 127.0.0.1. blog.anythingyoulike.com added our custom domain to the allowed host on our settings.py ALLOWED_HOSTS = ['www.anythingyoulike.com', 'blog.anythingyoulike.com', 'anythingyoulike.com'] But other devices on my hotspot network are unable to access using these domain names, and only my devices where I hosted my django website is able to access it. Note : There are Android mobile devices too where I want to access using domain name on my local environment -
Django re-calculate column on model anytime a new model is created or an existing is saved
I have a model that has an aggregate field on it. I'd like to recalculate the agg field whenever the model is updated, or calculate it initially if the model is being created. model (Just as an example): class FooBar(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField(blank=True, null=True) last_active_date = models.DateTimeField(blank=True, null=True) agg_field = models.DateTimeField(blank=True, null=True) Where the agg_field should be a method such as (This could be anything, just wrote this as an example): FooBar.objects.filter('last_active_date__gt': datetime.now() - timedelta(days=1)).annotate(Count('pk'))) So essentially every time the model is updated or created, it should recalculate this column -
Devspace deploy error: pullSecrets[0].registry: cannot be empty
I'm studying how to deploy a django application with kubernetes, I found this tutorial, which explains about the Devspace tool, so that following the tutorial just like it returns me a message that I can't solve. the message is this: returns only this [fatal] pullSecrets[0].registry: cannot be empty Can someone help me ? -
HTML5 Video tag not showing on Iphone Safari. like the video isn't loading
I am using Django. This is my code. The video is in mp4 format. <video autoplay loop muted playsinline class="mt-5" style="width:100%;margin:0 auto;"> <source src="{{ project.secondary_video_mobile.url }}" type="video/mp4"> </video> Is it something with apple devices? or any workaround for this issue? Note: i tried adding controls and preload="metadata" and didn't work. -
Getting Employee ID from Azure AD
I am able to retrieve the Job Title, Department. I want to be able to retrieve the Employee ID. As shown in the second image, I need to know the parameters to get the Employee ID. This is my HTML. <p>{{user.employee id}} </p> -
ThreadPoolExecutor results not aggregating properly
I'm trying to download multiple files at once in a Django (3.1.x) application, compiling the results to operate on later. I have this simple routine that downloads a file: import requests import tempfile def download_file(url): response = requests.get(url, stream=True, timeout=10) if(response.status_code == 200): ntf = tempfile.NamedTemporaryFile(delete=False) for chunk in response.iter_content(32768): ntf.write(chunk) ntf.flush() ntf.close() return ntf else: response.raise_for_status() Here's the core of the code that calls this method: from concurrent.futures import ThreadPoolExecutor, as_completed urls = [ "https://www.example.com/1.jpg", "https://www.example.com/2.jpg", # ... others ... ] external_map = {} with ThreadPoolExecutor() as executor: downloads = {executor.submit(download_file, url): url for url in urls} for download in as_completed(downloads): url = downloads[download] try: data = download.result() external_map.setdefault(url, data) except Exception as e: print(f"Failed to download {url}: {e}") print(external_map) When I run this code locally, the final print statement shows an empty dict for the external_map variable. Shouldn't there be two entries in it? My expectation after running the threads is that the resulting dict would look like: external_map = { 'https://example.com/1.jpg': NamedTemporaryFile<abc>, 'https://example.com/2.jpg': NamedTemporaryFile<def>, } What am I doing wrong? Could the toy Django webserver (python manage.py runserver) be messing with the results somehow? -
How can I check User Input value again Django Models and Forms
I don't know how to actually write the logic but I want to check user inputs especially price form field against Product model (price property). I have model the django form as below: class SalesForm(forms.ModelForm): class Meta: model = Sales fields = ['product', 'customer', 'quantity', 'price'] Here is the Product Model class Product(models.Model): name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=100, choices=CATEGORY, null=True) cost = models.PositiveIntegerField(null=True) price = models.PositiveIntegerField(null=True) quantity = models.PositiveIntegerField(null=True) Here is what I am trying to do logically in views.py def user_add_sales(request): sales = Sales.objects.all().order_by('-salesdate')[:5] if request.method == 'POST': sales_form = SalesForm(request.POST) if sales_form.is_valid: sales_price = sales_form.cleaned_data('price') try: user_input = Product.objects.get(price = sales_price) sales_form.save() messages.success(request, 'Sales Added Successfully') return redirect('dashboard-user-sales') except user_input.DoesNotExist: sales_form = SalesForm() else: sales_form = SalesForm() context = { 'sales' : sales, 'sales_form' : sales_form, } return render(request, 'dashboard/user_sales.html', context) When Try running the code, says 'SalesForm' object has no attribute 'cleaned_data'. Someone should please help. -
How to have multiple users in django with different attributes
I started using Django and what I want accomplish is a custom user model. I want three types of users and each one will have some attributes in common and also ones that are unique to each user. For example a customer will have a "comments" attributes while staff and admin won't. From what I read in the following article I would have to customize my user model so I do not have to suffer down the line if I want to make any changes. The article also shows how to make the email the username which is what I want but I am not sure if this is the best approach as I have no idea if it fits my use case. More specifically I do not know how to make each user have different attributes. From the following question I know I would need to have an attribute that describes the type of user but how would I link it to a profile? When creating users is my main concern, regular customers can register on the register page while admin and staff can be created by another admin only (I plan to use a custom made admin page … -
I have expirience strange error WebSocket
We are using Redis to send notifications in Django to users when there post is liked. After huge upgrade everything is working except of this: WebSocket connection to 'wss://PATHs/token' failed: I cannot open this path wss://PATHs/token locally and have no direction. -
Django initial loading of page taking too long
Hi I am a beginner at Django and I am working on a project that lists 100 companies in each page along with there contacts and also the amount of items sold. Here is an example: As you can see the initial loading time of the page is very high. But when I refresh the page it refreshes very fast because I am using caching. Here are some of my other files: models.py from __future__ import unicode_literals from django.db import models class Company(models.Model): name = models.CharField(max_length=150) bic = models.CharField(max_length=150, blank=True) def get_order_count(self): orders = self.orders.count() return orders def get_order_sum(self): orders = Order.objects.filter(company=self) total_sum = sum([x.total for x in orders]) return total_sum class Meta: ordering = ['-id'] class Contact(models.Model): company = models.ForeignKey( Company, related_name="contacts", on_delete=models.PROTECT) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150, blank=True) email = models.EmailField() def get_order_count(self): orders = self.orders.count() return orders class Order(models.Model): order_number = models.CharField(max_length=150) company = models.ForeignKey(Company, related_name="orders", on_delete=models.CASCADE) contact = models.ForeignKey(Contact, related_name="orders", on_delete=models.SET_NULL, blank=True, null=True) total = models.DecimalField(max_digits=18, decimal_places=9) order_date = models.DateTimeField(null=True, blank=True) added_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return "%s" % self.order_number views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView from mailer.models import Company, Contact, Order class IndexView(ListView): … -
Python doesn't remove file and raises no exception in Django view
I want to remove a file in django view as follows: class RemoveAPI(APIView): def get(self, request): ... os.remove(path='/opt/project/back_media/exports/excel_export.xlsx') return Response("deleted") The code runs without raising any exceptions but, when I see media directory, the file is there yet. I mean the file is not deleted. Note 1: if I add another os.remove(path='/opt/project/back_media/exports/excel_export.xlsx') before return statement, python raise FileNotFound error while file is in the media directory. Note 2: this is a django project that runs with Docker Compose. -
Django FloatField object has no attribute Error
I was creating a form in which user will input float number. My Code: class ApartmentForm(forms.ModelForm): ... val1= forms.FloatField( required=True, widget=forms.FloatField(), ) val2= forms.FloatField( required=True, widget=forms.FloatField(), ) But I am getting this error. AttributeError at /post/ 'FloatField' object has no attribute 'is_hidden' -
CSS Custom Button Colors
I'm trying to change the color of this specific button to blue (the facebook button which is called btn btn-primary mb-2), however, I'm unable to access its class file. Here is the HTML code and button CSS <div class ="login"> <div class="form"> <form class="login-form"> <input type="text" placeholder="Username" /> <input type="password" placeholder="Password" /> <p class="forgot-password"><a class= "fgt-password" href="">Forgot Password</a></p> <button class="login-btn">Login</button> <h7>--------------------------------- OR ---------------------------------</h7> <button class="btn btn-primary mb-2"> <a href="{% url 'rango:facebook_login' %}">Login with Facebook</a> </button> </form> </div> </div> And this is the CSS code .form button { font-family: "Lato", sans-serif; text-transform: uppercase; outline: 0; background: #006600; width: 100%; border: 0; padding: 15px; color: #FFFFFF; font-size: 14px; -webkit-transition: all 0.3 ease; transition: all 0.3 ease; cursor: pointer; } I tried .btn-primary or .form btn-primary but none work. Any ideas how I can access the class through CSS? -
__init__() got an unexpected keyword argument 'headers' (Django 3.2)
In my django web app, I create a .csv file from a list in my views.py and I want the user to be able to download it when the button is pressed. However, when this is run, I get the error that 'headers' is an unexpected argument. This is the code in my views.py: output = ['a', 'b', 'c'] response = HttpResponse(content_type='text/csv', headers={'Content-Disposition': 'attachment; filename="myfile.csv"'}) writer = csv.writer(response) writer.writerows(output) return response I have no idea why this doesn't work, since I have used identical code elsewhere with success in the past. Does anyone know if this could be a browser support issue? -
Why my django heroku app is not getting any staticfile. [error 404]
Everything of my django app is working fine on local machine with debug set to false DEBUG=False ,but after deploying on heroku app is running but not loading any static file.On logs it's showing status=404 for eg. static/style.css, for all static files. Can anyone please guide. I'm not using whitenoise or any staticfileshandler. my settings.py import os from pathlib import Path import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'key' DEBUG =False ALLOWED_HOSTS = ['127.0.0.1','myappname.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.myappConfig', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env=dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT=os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'myapp/static'), ) DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT … -
Values not loading/filling in appropriate form fields in Browsable Page in Django rest framework
I have these nested serializers, in which the fields are not appropriately maped to html form fields in browsable API page of django rest_framework, class NestedtLocationSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' fields = ( 'type', 'is_mobile', 'name', 'address', 'geometry', ) class NestedFloorplanSerializer(serializers.ModelSerializer): class Meta: model = FloorPlan fields = ( 'floor', 'image', ) class DeviceLocationSerializer(serializers.ModelSerializer): location = NestedtLocationSerializer() floorplan = NestedFloorplanSerializer() class Meta: model = DeviceLocation fields = ( 'location', 'floorplan', 'indoor', ) with the above serilaizers, I am getting this:- Response:- But in the html form fields the values of is_mobile, type, name are not loading in the html form fields:- Is there any way, I can controll the mapping of these fields to values?? -
stack inline 2 models each other which have a common onetoone field to another model
class User: .... class Profile: user = models.OneToOneField(User, on_delete=models.CASCADE) class Job: user = models.OneToOneField(User, on_delete=models.CASCADE) I have stackinline profile and job within the user model directly. but trying to stackinline Job under Profile model didnt work -
Docker is not saving django media files into project 'media' directory on production
App Description I have an app with django-gunicorn for back-end and reactjs-nginx with front-end all containerized as well as hosted on aws ec2 instance. Problem On development environment, media files are being saved in the 'media' directory permanently. Tho, those files are only saved on the current running docker container on production time. As a result, the files will be removed when I rebuild/stopped the container for a new code push. Expectation I wanted to store the file on the 'media' folder for permanent use. Important code settings.py ENV_PATH = Path(__file__).resolve().parent.parent STATIC_ROOT = BASE_DIR / 'django_static' STATIC_URL = '/django_static/' MEDIA_ROOT = BASE_DIR / 'media/' MEDIA_URL = '/media/' docker-compose-production.yml version: "3.3" services: db: image: postgres restart: always #Prevent postgres from stopping the container volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 5432:5432 nginx: restart: unless-stopped build: context: . dockerfile: ./docker/nginx/Dockerfile ports: - 80:80 - 443:443 volumes: - static_volume:/code/backend/server/django_static - ./docker/nginx/production:/etc/nginx/conf.d - ./docker/nginx/certbot/conf:/etc/letsencrypt - ./docker/nginx/certbot/www:/var/www/certbot depends_on: - backend # Volume for certificate renewal certbot: image: certbot/certbot restart: unless-stopped volumes: - ./docker/nginx/certbot/conf:/etc/letsencrypt - ./docker/nginx/certbot/www:/var/www/certbot entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" backend: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile … -
How to show a text by pushing a button on the same webpage, button is on a popup on Folium map
As you all know we can print a text on the same webpage by this code on the HTML: <body> <button onclick="myFunction()">Click me</button> <h1 id="myHeader"></h1> <script> function myFunction() { document.getElementById("myHeader").innerHTML = "hi"; } </script> </body> In my code the button is on the popup on the Folium map which looks like this: So, I would like to write "hi" on the h1 tag, onclick function for this button "More info!" on the same page: in HTML file: <h1 id="myHeader">SSSSSS</h1> <div> <form name="AAA" > <center> {{ map| safe }} </center> </form> </div> <script> function showsth() { document.getElementById("myHeader").innerHTML = "hi"; } </script> And I am using Django, so, the I predefined the popup like this: In views.py: popup_t = (... + '<button onclick="showsth()">More info!</button>' ) test = folium.Html(popup_t, script=True) popup = folium.Popup(test, min_width=150, max_width=500) So, when I click on the button, I didn't get any response just like I showed in the first HTML code. Do you have any idea about the problem? -
Django Login page looping
I created a user base with login and registration page, and everything worked fine, i was able to click on the logout button and it would log me out to the login page, but now it stopped, and I cant seem to even access The login page as I get the following error in CMD: [04/Aug/2021 17:21:22] "GET /Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Login/%2525253Fnext%2525253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Login/%2525253Fnext%2525253D/Login/%252525253Fnext%252525253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Login/%2525253Fnext%2525253D/Login/%252525253Fnext%252525253D/Login/%25252525253Fnext%25252525253D/Logout/ HTTP/1.1" 302 0 What I understood is that it redirects you to your login page, which isn't public. Which then redirects you again back to the login page, so on and so on. But I cant understand what is wrong with my code. VIEWS: @login_required(login_url='Login') def Auditor(request): model = datas.objects.filter(qs_login=request.user) form = auditForm() if request.method == "POST": form = auditForm(request.POST) if form.is_valid(): form.save() # <-- Add this to get the updated data instance context = {'items': model, 'form': form} return render(request, "main/auditform.html", context) @login_required(login_url='Login') def auditFormPage(request, pk): model = datas.objects.filter(qs_login=request.user) form = … -
Graphql bottleneck performance with nested query (Django + React ) makes frontend app unusable. Please help :'(
For this project Im using Python+Django and GraphQL (graphene) in the backend, MySQL as database and React.js for the frontend. In the frontend, after user logs in, I have the following query to be executed: const GET_ORGANIZATION = gql` query getOrganization($orgId : Int!) { organization(id:$orgId){ id name user{ id username firstName lastName email dateJoined lastLogin isActive trainings { id name sessions { id name category createdAt totalSteps completedAt user { id } eventSet { id category description object errorSeverity performedAt } } } } courses{ id name description trainings{ id name user{ id username isSuperuser isStaff isActive email } sessions{ id name category createdAt completedAt user{ id username } eventSet { id category description object errorSeverity performedAt } } } } } }`; As you can see, it has several levels nested. The problem comes when I go into sessions and events . I am not super expert with graphQL but I always thought the selling idea of GraphQL was that you can use all these nested fields in one single query. Well, it's not. Here are few images why: It takes over 30 seconds for the response to come. Digging a bit more into the slow_log of my database, … -
How to fix CORS Error on Django and Django REST Framework
I sometimes get CORS Error from the server, when I turn on a VPN I get 200 and when I change the VPN or when I turn it off I get CORS Error again, How can I fix CORS Error on Django and DRF. I have tried some ways and some references like: How can I enable CORS on Django REST Framework https://dzone.com/articles/how-to-fix-django-cors-error#:~:text=A%20request%20for%20a%20resource,has%20blocked%20by%20CORS%20policy. https://github.com/adamchainz/django-cors-headers but it isn't solved. what shall I do? -
Select a particular data using xpath
This is the element from a webpage <div class='someclass'> <section> <h4>Skills</h4> <p>Python, java, django</p> </section> <section> <h4>Prerequisites</h4> <p>Coding</p> </section> </div> I am trying to extract the skills from this using xpath. How can I achieve it? my answer should be: Python, java, django -
Django - After login, I get an error message saying This page isnt working on Google Chrome
I get an error message on the web browser after trying to login to my application. The error message is - This page isn’t working d1bbcb8e2c574d65bcfc28f937c87503.vfs.cloud9.us-east-2.amazonaws.com redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS My views is below # Views from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from powercons_app.EmailBackEnd import EmailBackEnd def loginPage(request): return render(request, 'login.html') def doLogin(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password')) if user != None: login(request, user) user_type = user.user_type #return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password')) if user_type == '1': return redirect('admin_home') # elif user_type == '2': # # return HttpResponse("Staff Login") # return redirect('staff_home') # elif user_type == '3': # # return HttpResponse("Client Login") # return redirect('client_home') else: messages.error(request, "Invalid Login!") return redirect('login') else: messages.error(request, "Invalid Login Credentials!") #return HttpResponseRedirect("/") return redirect('login') def get_user_details(request): if request.user != None: return HttpResponse("User: "+request.user.email+" User Type: "+request.user.user_type) else: return HttpResponse("Please Login First") def logout_user(request): logout(request) return HttpResponseRedirect('/') #Admin View from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.contrib import messages from django.core.files.storage import FileSystemStorage #To upload Profile Picture from django.urls import reverse … -
Django - How to ignore autmoatic model language filter
My application have three different languages I want to ignore the model translation automatic filter by the framework to get all data and not by activated translate. # LANGUAGES LANGUAGES = ( ('ru', _(u'Русский')), ('en', _(u'English')), ('cn', _(u'漢語')) ) def get_queryset(self): queryset = super(ModelView, self).get_queryset().order_by('-pub_date').only('city_ru') return queryset Before queryset get executed I've tried translate.activate('ru') to get 404 not found if user tried to switch to another language, but I want to keep the same data for all languages no matter if the user switched or not the text on website will be translated but data will still the same.