Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django select related of select related
I have a Student model which has a foreign key to a School model (related name is school) which has itself a FK to a Country model (related name is country). I want to select the Student along with its school and country. Do I need to write this: student = Student.objects.filter(pk=123).select_related("school", "school__country").first() student.school # use object cache student.school.country # use object cache or is this enough: student = Student.objects.filter(pk=123).select_related("school__country").first() -
Django unable to upload image file
I was trying out InageField in the models, But Image upload do not work when I try to upload from the forms. But it works when I upload it from the admin page. Any way to debug is also helpful My model- class Inventory(models.Model): """docstring for Inventory""" name = models.CharField(max_length=100,default='Something') image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=100, default='Describe Something') price = models.IntegerField( default=0) My Form- class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = ['name','description','price','image'] widgets = { 'name' : forms.TextInput(attrs={"placeholder":"Name", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}), 'description' : forms.TextInput(attrs={"placeholder":"Email", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}), 'price' : forms.NumberInput(attrs={"placeholder":"Price","onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}), } Settings - MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media/") template - <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="Send"> </form> url - from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('inventory.urls')), path('<int:id>',include('inventory.urls')), path('admin/', admin.site.urls), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Regards, Deepak Dash -
Geodjango: transform() swaps lat/long incorrectly
I'm using geodjango and load a shapefile as follows: datasource = DataSource("/path/to/shape.shp") for each in datasource[0]: geo = each.geom geo.transform(4326) What I'm trying to do here is to transform a geometry to 4326 so I can record it in my database, which uses this SRID. However, a rather odd thing happens. When I run this locally (using GDAL 2.4.0, Django 3.0.6) this works perfectly fine. Here is an example of a polygon that is transformed. Input: POLYGON ((141192.63413501 167690.231242441,141198.39365501 167695.515882441... Which is then transformed into: POLYGON ((4.24376514198078 50.8195815928706,4.24384675060931 50.819629186136... This works well. However, when this runs in production (GDAL 3.0.4, Django 3.0.3), then this fails in a very weird way. There is no error message, and the transform() function does its thing... but it reverses latitude and longitude! So my output becomes: POLYGON ((50.8195818670687 4.24376485512428,50.8196294603646 4.24384646375124... I can not fathom why this happens...?! It all seems to be fine, expect for this very odd swapping of lat/long. -
Search a generated format in Django Database
In my django app I am creating Barcodes with a combination of str and id of model and id of product. The barcode is generated but the problem that I am encountering is when I scan the barcode I want to show the information of the product scanned. I'll be able to understand the problem with code in a better way Models.py class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) reference_no = models.CharField(max_length=500, default=0) items = models.ManyToManyField(GrnItems) Views.py def PrintGRNsv1(request, pk): grn = Grn.objects.filter(pk=pk)[0] grn_prod = grn.items.all() print("grn prod", grn_prod) items = [] for i in grn_prod: for j in range(i.item_quantity): items.append({'bar': "YNT9299" + str(pk) + str(i.item.pk) + str(j + 1)} ) Now let's suppose I generated a Barcode YNT92991231, Now I have no idea how to get the i.item.pk from this code How can I do this ? -
heroku invalid phone number
when deploying an app with add-ons it tells me The account "****@." is not permitted to install the sendgrid add-on at this time. Your account may require additional verification. Please visit https://tools.heroku.support/addons-verification to complete this process. It asks me for my phone number , but when entering it , i see " This number is not supported. Please contact support. " -
What happens If an SQL query takes more time and the left age of CONN_MAX_AGE is less?
Using: Django 1.10 and MySQL I would like to timeout a query when a particular query takes longer time. One closest thing I found is this. https://docs.djangoproject.com/en/1.10/ref/settings/#conn-max-age CONN_MAX_AGE The lifetime of a database connection, in seconds. Use 0 to close database connections at the end of each request — Django’s historical behavior — and None for unlimited persistent connections. Let's assume the following scenario: CONN_MAX_AGE is set to 5 seconds On an average, each DB query takes 3 seconds. Request #1 comes in and since there is no active conn, It creates a connection and set the connection age to 5 seconds. Request #1 finishes after 3 seconds and age left for conn to expire is 2 seconds. Now, Request #2 comes in, Since the conn is available it uses the old open conn. Now, What happens to Request #2? Will it finish successfully or Will it terminate because the conn this query is using has less time left to expire? -
How to made updates to a site deployed on digital ocean [closed]
I have django website hosted on digital ocean. I want to make some changes to the static html page and database. Can i use filezilla to do this? What would be the easiest method to do this updates. Please guide me -
1049, "Unknown database 'tester_gk1chOZhTJ4l'" when trying to access db view from a user in django
I am using multiple dbs and changing databases based on specific users/vendor permissions in Django. I am able to create dbs and models dynamically. 1046, 'No database selected' - unable to create programmatically the models (created with models.Model definition) The db model was created but when accessing the data in the view I get the same error. Seems like the database is not changed dynamically. Here is the code I am using class RouterMiddleware(MiddlewareMixin): def process_view(self, request, view_func, args, kwargs): requser = request.user try: userobj = User.objects.get(username=requser) except: userobj = None if userobj: try: usr = CompanyUser.objects.filter(user=userobj)[0] except: usr = None if usr: request_cfg.cfg = { "id": usr.company.db_name, "ENGINE": usr.company.engine, "NAME": usr.company.db_name, "USER": usr.company.user, "PASSWORD": usr.company.password, "HOST": usr.company.host, "PORT": usr.company.port, "ATOMIC_REQUESTS": False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, usr.company.db_name: { 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None } } else: request_cfg.cfg = {"id": 'default'} if not request_cfg.cfg.get("id") in settings.DATABASES: from django.db import connections connections.databases[request_cfg.cfg.get( "id")] = request_cfg.cfg settings.DATABASES.update({ request_cfg.cfg.get("id"): request_cfg.cfg }) The middlewares and db routers are registered. class DatabaseRouter (object): def _default_db(self, model): apps = ["auth", "sessions", "contenttypes", "admin", "setupsaas"] if hasattr(request_cfg, 'cfg'): if request_cfg.cfg.get('id') != None: if model._meta.app_label in apps: return 'default' return request_cfg.cfg.get('id') else: … -
TypeError at / 'ModelBase' object is not iterable .....How to resolve thsi in django
TypeError at / 'ModelBase' object is not iterable .....How to resolve this in django? Here is my models.py:- from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views.py:- import requests from django.shortcuts import render from . models import City Create your views here. def home(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=37dcd1bbdc2216925ebb043a870105a6' cities = City.objects.all() weather_data = [] for city in City: city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'] } weather_data.append(weather) context = {'weather_data' : weather_data} return render(request,'home.html',context) Please solve this as i am a beginner in Django -
In JavaScript code combining two functions not working, but in single function works fine
CS50 WEB's project3 mail When I use single funciton it works properly which is function compose_email() { // Show compose view and hide other views document.querySelector('#read-view').style.display = 'none'; document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; document.querySelector('#compose-form').onsubmit = function() { let recipient = document.querySelector('#compose-recipients'); let subject = document.querySelector('#compose-subject'); let body = document.querySelector('#compose-body'); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipient.value, subject: subject.value, body: body.value, }) }) .then(response => response.json()) .then(result => { console.log(result); }); load_mailbox('sent') return false; }; }; But when I split it into two function it doesn't load load_mailbox('sent') function compose_email() { // Show compose view and hide other views document.querySelector('#read-view').style.display = 'none'; document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; document.querySelector('#compose-form').onsubmit = function() { send_email(); }; }; function send_email() { let recipient = document.querySelector('#compose-recipients'); let subject = document.querySelector('#compose-subject'); let body = document.querySelector('#compose-body'); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipient.value, subject: subject.value, body: body.value, }) }) .then(response => response.json()) .then(result => { console.log(result); }); load_mailbox('sent') return false; }; -
Sending data from search bar to url
I need to send the raw text from a search bar input to my url, but I am getting query strings and I can't figure out how to convert it into text I can use This is the html that handles said bar <form method ='GET' action="/entry/"> <input class="search" type="text" placeholder="Search Encyclopedia"> </form> -
django channels emoji and images [closed]
I would like to send emojis and images in Django channels chat app, Is it possible to do with the integration of Django-ckedior, any help would be great, thanks! -
django template get key and value seperate to display
In django template i am getting the value like : {"A":"12","B":"13"} how can i display values in template through loop like : A - 12 B - 13 Can anyone have any idea please help me related this -
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. In django 2.2
I'm facing this issue in test server. but not in production. I tried some of the solutions like python manage.py runserver --noreload and edit /lib/python3.6/site-packages/django/utils/autoreload.py this file. Mentioned in the document. https://github.com/django/django/commit/5bf2c87ece216b00a55a6ec0d6c824c9edabf188 This the error message look like, sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 140000522213120 and this is thread id 140000744696768. Please suggest me a solution to rectify this problem, Anyone faced this issue before. Help me to solve this issue. -
django.urls.exceptions.NoReverseMatch:
I'm trying to create custom multiple user types registration and I keep running into this error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. The main issue is I have not yet created any 'login' view function Here are my project urls `from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), ]` and these are my app's urls from django.urls import path from . import views urlpatterns = [ path('register/',views.register,name='register'), path('customer_register/',views.customer_register.as_view(),name='customer_register'), path('business_register/',views.business_register.as_view(),name='business_register'), ] these are the relevant view functions from django.shortcuts import render from django.views.generic import CreateView from .forms import Customer_userRegisterForm,Business_userRegisterForm from .models import User,Business,Customer def register(request): return render(request,'users/register.html') class customer_register(CreateView): model = User form_class = Customer_userRegisterForm template_name = 'users/customer_register.html' class business_register(CreateView): model = User form_class = Business_userRegisterForm template_name = 'users/business_register.html' I have tried to look at solutions to similar questions but none works for me. please help me solve the problem. -
NodeJS or Django for machinelearning and API?
I am developing a project in which FrontEnd is Flutter app and I want to make a backend with machine learning and Mongo DB. I know Django and Nodejs both. I tried Django REST Framework but didnt like it at all as I am used to make APIs in NodeJS as my database is also MongoDB. I consider NodeJS to be good for making REST APIs and Python good for machine learning. Spawning child processes is not a great idea please suggest one language that can I use for my project backend. -
HTML barcode scanner to input field
I was just wondering if there is any way to have a barcode scanner input in my Django project. I want to be able to be able to scan a barcode from a mobile device and have the value of that code to occupy an input field where the user can then search. Any help is appreciated cheers -
Nodejs Templating
As in Django template inheritance, we can use base_template, right?. We can pass content to base_template and it returns with an updated template. Can we do the same in NODEJS? I know we can pass params and use that in individual templates. -
Toggle switch on and off from Django model using jquery
I have the below in my model.py from which I have the boolean value (tunnel_status): class IPSEC(models.Model): tunnel_name = models.CharField(max_length=100) tunnel_ip = models.CharField(max_length=100) tunnel_acl = models.CharField(max_length=100, default='acl') tunnel_acl_conf = models.CharField(max_length=1000, default='access-list 1') tunnel_status = models.BooleanField(default=False) I have the below in my HTML form (Have paste only the relevant code): {% for items in ipsec %} <tbody> <tr> <td>{{ items.tunnel_name }}</td> <td class="text-center">{{ items.tunnel_ip }}</td> <td class="identifyingClass"><a data-toggle="modal" data-target="#myModal{{ items.id }}" href="/ipsecacl/?acl={{ items.tunnel_acl }}">{{ items.tunnel_acl }}</a></td> <td> <label class="switch"> <div id="statvalue">{{ items.tunnel_status }}</div> <input type="checkbox" id="stats"> <span class="slider round"></span> </label> </td> </tr> {% endfor %} basically, I want to toggle the switch in the table base on the boolean values True = switch on and False = switch off. I know I have to use Jquery to accomplish this. But I lack a bit of knowledge on this. -
Django Form Field Not Setting Value After Submitting
I'm trying to post data from a form that contains incomplete data (I set the missing data in the View class before saving) for the following model. But the form does not get submitted as it is invalid (it's missing the harvest_amount, but I set the value on the webpage before submitting. class Harvest(models.Model): harvest_amount = models.IntegerField(validators=[MinValueValidator(limit_value=0)]) harvest_date = models.DateField() harvest_for_plant = models.ForeignKey(Plant, on_delete=models.CASCADE) and my form class HarvestCreationForm(forms.ModelForm): class Meta: model = Harvest fields = [ 'harvest_amount' ] def is_valid(self): //check if Id in the url contains a valid id for a plant return True -
Django how to get absolute urls in template?
I want to have on "courses.html" template 2 different objects, category and course so the urls for each category should look like "0.0.0.0:8000/category/python" but instead it is "0.0.0.0:8000/courses/python". Is there any way to have a proper absolute url from object? main views.py def courses(request): return render(request=request, template_name="main/courses.html", context={'courses': Course.objects.all, 'categories': Category.objects.all}, ) courses.html {% extends "main/header.html" %} {% block content %} {% for category in categories %} <a href="{{ category.slug }}"/> <p>{{ category }}</p> </a> {% endfor %} {% for course in courses %} <a href="{{ course.slug }}"/> <p>{{ course }}</p> </a> {% endfor %} -
Django - How do I order results by a SerializerMethodField field in a ViewSet?
I have a complicated logic to compute the custom field location in AdSerializer and a complicated logic to get the final queryset in AdViewSet. How can I order the final result by location before returning it? class AdSerializer(serializers.ModelSerializer): location = serializers.SerializerMethodField() def get_location: # logic to get a location of the ad class AdViewSet(viewsets.ReadOnlyModelViewSet): queryset = Ad.objects.filter(...) serializer_class = AdSerializer def get_queryset(self): # logic to compute the final result return queryset -
Django, Ajax populate search results via .js with model data
I am new at the JS world and need help using AJAX to populate search results from my models data. In essence, when a user types something in the search form, the data filters through asynchronously with 'title__istarts_with' providing the correct options. I'm having trouble with how to dynamically populate the data with the correct syntax on the search-results.js with the html setup. this is my home.html: <div class="app-table"> <div class="row"> {% for pilot in pilots %} <div class="col-lg-4"> {% if pilot.poster %} <img class="thumbnail" src="{{ pilot.poster.url }}"> {% endif %} <div class="box-element product"> <p>{{pilot.title}}</p> <p>Page Count: {{pilot.count}}</p> <p>Creator: {{ pilot.writer }}</p> {% if pilot.script %} <a href="{{ pilot.script.url }}" target="_blank">Read Me</a> {% endif %} </div> </div> {% endfor %} </div> </div> this my search_results.js: const sbody=document.querySelector(".search-body") ... if(data.length===0){ searchOutput.innerHTML = "Sorry, mate. Script hasn't been donated yet!"; }else{ data.forEach(item=>{ sbody.innerHTML += ' <div> <p>${pilot.title}</p> <p>${pilot.count}</p> <p>${pilot.writer}</p> </div>'; }) } ... I also don't know the right syntax to populate the img and url tags? -
How does Django ORM pass raw SQL queries through Psycopg2?
When using psycopg2 as the database connector specified in a DATABASES constant in settings.py, how do raw SQL queries get handled? When you use django.db.connection and cursor.execute(), does it use Django's classes to handle things, or psycopg2s? -
How Should I install Djnago on Ubuntu 20.04 LTS
I am tried to install Djnago on ubuntu 20.04 LTS version. First of all I used the below code for install Python and that is, sudo apt-get install python3 Python version is 3.8.2. Then I used two steps for install Django, 1st step: sudo apt update 2nd step: sudo apt install python3-pip Error is showed in 2nd step and that is, Media change: please insert the disc labeled 'Ubuntu 20.04.1 LTS _Focal Fossa_ - Release amd64 (20200731)' in the drive '/cdrom/' and press [Enter] When I press Enter. It continuously showed but don't solved my problems. Now What should I do,please help me for solving this problem.