Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Cannot use None as a query value django ajax
I want to show the dropdown list with data response via Ajax call. Everything is working fine but I am getting this ValueError: Cannot use None as a query value error. view: def load_brand(request): if request.is_ajax(): term = request.GET.get('term') brand = Brand.objects.all().filter(brand__icontains=term) return JsonResponse(list(brand.values()), safe=False) ajax: $('#id_brand').select2({ ajax: { url: '/brand/ajax/load-brand/', dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.brand}; }) }; } }, minimumInputLength: 1 }); -
I finished AWS web service and test to enter domain web site and this error message popped up in chrome developer tool
this is the architecture used in AWS how I configured AWS VPC VPC’s private ip range : 172.31.0.0/16 1 public subnet 3 private subnets how I configured AWS route table private subnet route table configuration ->172.31.0.0/16 local ->0.0.0.0/0 NAT gateway -included subnets → frontend private subnet / backend private subnet / RDS private subnet total 3 private subnets included in private route table public subnet route table → 172.31.0.0/16 local → 0.0.0.0/0 internet gateway → public subnet that contains Application Load Balancer / bastion host ec2 / NAT gateway total 1 public subnet included in public route table How I configured Application Load Balancer internet facing connected instance : frontend ec2 instance in private subnet then all the configuration done I entered domain web site to test it then I confronted with this error [Vuetify] [UPGRADE] ‘v-content’ is deprecated, use ‘v-main’ instead. console.ts:34 ***found in *** —> VMain *** VApp*** *** App*** *** Root*** POST ‘http://ec2-xxx-xxx-xxx-xxx.us-west-1.compute.amazonaws.com:8000/Product/item_list’ xhr.js:177 !net::ERR_CONNECTION_REFUSED! !Uncaught (in promise) Error:Network Error createError.js:16 *** at t.exports (createError.js:16)*** *** at XMLHttpRequest.d.onerror (xhr.js:84) !*** POST ‘http://ec2-xxx-xxx-xxx-xxx.us-west-1.compute.amazonaws.com:8000/Bag/bag_count’ xhr.js:177 net::ERR_CONNECTION_REFUSED Uncaught (in promise) Error: Network Error createError.js:16 *** at t.exports (createError.js:16)*** *** at XMLHttpRequest.d.onerror (xhr.js:84)*** my question is Q. what is the problem … -
Django images not showing up
I've spent hours looking for a solution, figured I would post for myself. Django images won't show. models.py: class Item(models.Model): ... image = models.ImageField(default='default.jpg', upload_to='item_pics') urls.py from django.urls import path from . import views from .views import ItemListView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', ItemListView.as_view(), name="site-home"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html-file {% extends "ui/base.html" %} {% load static %} {% block content %} <ul> {% for item in items %} <li> <p><img src="{{ item.image.url }}"></p> <br> </li> {% endfor %} </ul> {% endblock content %} It shows up like this: When I copy image address, I get http://localhost:8000/media/default.jpg -
How to extend base.html in django
Quick question, while extending base.html to my other pages in my django project the base.html page takes over and i can only see the base.html page. i only see the other pages/templates when i remove the extension. what am I doing wrong? I realise this might be a stupid question to some but just help out if you can. Thank you -
Permission denied in jailshell
I'm installing my Django project on my hosting but when I want to activate the virtual environment the console marks this error: jailshell: .virtualenv/bin/activate: Permission denied. And I don't know how to fix it, I'm using it through the cpanel. Thanks -
Not Found: /particles.json
I am trying to build a forum with Django. I want to use an animated background with particles.js. When I write this code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Particles login</title> <link rel="stylesheet" href="style.css"> </head> <body> <div id="particles-js"> </div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', 'particles.json', function(){ console.log('particles.json loaded...'); }); </script> </body> </html> and run it on live server I get what I want. However, I tweaked the code for Django: <!DOCTYPE html> <html lang=en> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> </head> <body> {% include 'snippets/base_css.html' %} {% include 'snippets/header.html' %} <!-- Body --> <style type="text/css"> .main{ min-height: 100vh; height: 100%; } #particles-js{ height: 100%; color:turquoise; } </style> <div class="main"> <div id="particles-js"> </div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', 'particles.json', function(){ console.log('particles.json loaded...'); }); </script> {% block content %} {% endblock content %} </div> </div> <!-- End Body --> {% include 'snippets/footer.html' %} </body> </html> When I run this with Django. I get the following error even though the locations of those files are exactly the same: Not Found: /style.css [28/May/2021 00:21:59] "GET /style.css HTTP/1.1" 404 2263 Not … -
What does Django use as a Cache Key?
I'm caching Wagtail API endpoints using Django's standard cache_page function which looks something like this: @method_decorator(cache_page(600), name="detail_view") @method_decorator(cache_page(600), name="listing_view") class CashedPagesAPIViewSet(PagesAPIViewSet): """Custom API endpoint that can receive a slug.""" pass Very basic. I want to be able to clear the API cache on each page save, but I don't know how to get the cache key. I can clear all the cache with this: from django.core.cache import cache from wagtail.core.signals import page_published def clear_cache(sender, **kwargs): """Clear page cache.""" cache.clear() page_published.connect(clear_cache) What I want to be able to do is: def clear_cache(sender, **kwargs): """Clear page cache.""" page = kwargs["instance"] cache.delete(f"/api/v2/pages/{page.id}") # or whatever the key might be -
Django APP Heroku Log detecting duplicated requests
I have a Django APP running on Heroku. I noticed that when I make some requests, there seems to be a sort of duplicated call with extra info in the url. Which of course is not found. I will explain here showing Heroku´s log details. The first request works fine and the APP does what it´s supposed to do. Notice the path ending: /3/ 2021-05-28T00:05:49.833310+00:00 heroku[router]: at=info method=GET path="/catalog/toma-pedidok-detail/7650/Proxima%20fase/3/" host=www.host.com request_id=ef1018b5-456a-4559-89e6-830b256671fd fwd="181.168.190.149" dyno=web.1 connect=1ms service=1971ms status=200 bytes=160294 protocol=https Then the "ghost" request happens and the path ending has the extra characters: /3/636 2021-05-28T00:06:02.494246+00:00 heroku[router]: at=info method=GET path="/catalog/toma-pedidok-detail/7650/Proxima%20fase/3/636" host=www.host.com request_id=222035b1-2ea8-405d-b8b2-c47fc2376aba fwd="181.168.190.149" dyno=web.1 connect=2ms service=83ms status=404 bytes=11585 protocol=https Finaly we have a logical "not found" response. 2021-05-28T00:06:02.491918+00:00 app[web.1]: Not Found: /catalog/toma-pedidok-detail/7650/Proxima fase/3/636 Some checks It happens sometimes, not always There is no ajax call related with this url target Django´s view only has 1 return statement I don´t include all the view because it´s quite extense. I´m trying to get a clue about why can this be happening first. Any clues welcome. Thanks in advance! -
Is it possible to stack either formset_factory, inlineformset_factory - Django
As the question says, i haven't found any info about stacking either formset_factory, inlineformset_factory into either formset_factory, inlineformset_factory maybe someone in here might know something about it? :o -
Frontend Framework like react, vue in python
I am trying to shift in python for web development. But I love to use React in Frontend Side. I would Love to Know if there is any Frontend Framework or library design in python. Reason I am Shifting is that i am into data science and don't want to remember Lot of logic of different language. If there is any with high working potential it would be great. Thank You -
send event id of eventClick to views.py Django
I'm really new in Javascript and Fullcalendar and I need to know how to pass the event id of the clicked event (event_id) to the views.py. so for now I'm having that: document.addEventListener('DOMContentLoaded', function () { var calendarUI = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarUI, { eventClick: function (info) { alert('Event: ' + info.event.id); var event_id = info.event.id; $('#exampleModalToggle').modal('show');} selectable: true, editable: true, displayEventTime: true, displayEventEnd: true, contentHeight: "auto", allDaySlot: false, initialView: 'timeGridWeek', headerToolbar: { left: 'today', center: 'prev title next', right: 'dayGridMonth timeGridWeek' }, views: { timeGridWeek: { //titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' } columnHeaderFormat: { weekday: 'numeric', month: 'numeric', day: 'numeric', omitCommas: true } } }, //slotLabelFormat: [{ month: 'long', year: 'numeric' }, { weekday: 'short' }], //slotLabelFormat: ['ddd D/M', 'H:mm'], events: [ {% for reservation in reservations_api %} { title: '{% for machine in machines %} {% if reservation.machine_id == machine.id %} {{machine.machine_name}} {% endif %} {% endfor %} - {% for enterprise in enterprises %} {% if reservation.company_id == enterprise.id %} {{enterprise.name}} {% endif %} {% endfor %} ', start: '{{ reservation.start_date }}', end: '{{ reservation.end_date }}', color: '{% for enterprise in enterprises %} {% if reservation.company_id == enterprise.id %} {{enterprise.color}} {% endif … -
OpenCv videoCapture in cpanel (Incomplete response received from application)
Here I call Videocamera to open the camera and then return streaminghttpresponse and there i call gen(cam). Now i am facing 2 problem. i want to store 100 images of user and go back to another screen. here this code working locally fine but when i upload it on server its give error Incomplete response received from application and second problem is will render to another screen when count == 10 def getImages(request): global postReq postReq = request print(request) global userRequest global userFaceName userFaceName = request.POST['name'] print(userFaceName) userRequest = request.user.pk print(userRequest) try: cam = VideoCamera() print("hello check") return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: print("killed") pass return redirect('imagess') class VideoCamera(): def __init__(self): global count print("video camera") self.video = cv2.VideoCapture(0) print("video") (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): print("destriy") self.video.release() def get_frame(self): face_id=1 image = self.frame # face_detector = cv2.CascadeClassifier('C:\\Users\\abbas\\Desktop\\final try\\FYP\\isight\\Application\\haarcascade_frontalface_default.xml') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # faces = face_detector.detectMultiScale(gray, 1.3, 5) # for (x,y,w,h) in faces: # cv2.rectangle(gray, (x,y), (x+w,y+h), (255,0,0), 2) # global count # count = count + 1 # face = cv2.resize(image, (400, 400)) # face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY) # writePic = cv2.imwrite("static/pdfbook/images/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w]) # c = 'C:\\Users\\abbas\\Desktop\\final try\\FYP\\isight\\static\\pdfbook\\images\\' + "User." + … -
How to write this SQL lines in Django Models?
CREATE TABLE animal ( ID number not null primary key , GENDER varchar2(1) not null , SIRE_ID number , DAM_ID number , constraint animal_gender check (gender in ('M','F')) , constraint animal_sire_fk FOREIGN KEY (sire_id) REFERENCES animal(id) DEFERRABLE INITIALLY DEFERRED , constraint animal_dam_fk FOREIGN KEY (dam_id) REFERENCES animal(id) DEFERRABLE INITIALLY DEFERRED ); -
How can I make a tree data structure
I'm working on a small project (File Browser) using Django / Javascript. i have two models: from django.db import models # Create your models here. class Folder(models.Model): name = models.CharField(blank=False, null=False, max_length=60) parent = models.IntegerField(blank=False, null=False) class Document(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE, null=True, blank=True) filename = models.CharField(blank=False, null=False, max_length=60) I would like to have this data structure : root: { name: 'Files', children:[ { 'name': 'music', children:[ { name: 'song.mp3' }, { name: 'song2.mp3' } ] }, { name: 'Books', children:[ { name: 'php.pdf' } ] } ] } can someone help me to make it thank you -
How would you model in django a hierarchy of objects where one type might has itself as a child?
I would like to model the following hierarchy in Django, but don't really know how to approach the Opportunity relationships to other Opportunities and/or Solutions. Outcome |- Opportunity 1 | |- Opportunity 1.1 | | |- Solution 1 | | |- Solution 2 | |- Opportunity 1.2 | |- Solution 3 | |- Solution 4 |- Opportunity 2 |- Solution 5 |- Solution 6 Each outcome has many Opportunities. Each Solution belongs to an Opportunity. Opportunities might either have many Opportunities or many Solutions, but not both. Sub-opportunities can not have more Opportunities, just Solutions. -
Inner HTML with Django tamplate if statement usig Js variable
I'm really new in JavaScript and I have a question: I need to add inside an inner Html, a Django template if statement that uses a JavaScript variable to compare (in this case the variable is event_id) I have tried a lot of alternatives after hours and also I have searched with no success. This is my JS code. eventClick: function (info) { var event_id = info.event.id; $('#exampleModalToggle').modal('show'); selected_group_member.innerHTML = ` {% for reservation in reservations_api %} {% if reservation.id == ${event_id} %} <option value="1" selected>{{reservation.id}}</option> {% endif %} {% endfor %} `; } with this option, I'm getting this error: Could not parse the remainder: '${event_id}' from '${event_id}' and if I change it for {% if reservation.id == + event_id + %}, I'm getting this error: Could not parse the remainder: '' from '' So, is that possible to do? Do you know how could it work please !!! I really don't know how to solve it, I really appreciate your help thanks :) -
Should I start over my project in a new Django Virtual Environment
I began my project without creating a virtual environment. Now I am wondering how big of a mistake was that. pip install Pillow not executing no matter what I do to include an image in my classs Model. Can or should I migrate my files to a new virtual environment. Or should I start coding from scratch. -
How to add ''draw a marker" Control to leaflet Map and capture event?
I want to create a map with leaflet and give the user the opportunity to add a marker to that map from the user interface. The user shuld mark a point(market to th map). Then when the point is set I want to get the location (coordinates) of that marker and perform other operations. It should allow only one marker I want this result -
Why does this error appear in my JailedShell when installing Django?
The error that appears on the console I want to create a project in Django in my hosting, I was investigated that it was what I had to do using JailedShell in cpanel, but at the time of installing it does not work and i mark the errors that are in the image that I attach. When I asked in my hosting they sent me this link step by step what I have to do to install Django is its version 1.11 since the hosting is using python 2.75, I followed the steps of the article but I do not understand well, likewise, leave the link of the article here https://soporte-latam.hostgator.com/hc/es-419/articles/115002998391#pasoinicial Hoping someone can help me, thank you very much -
cant connect stripe webhook with heroku
iam currently deployed my website on Heroku but after the user pay for the order Stripe Webhook dosent work at all although it worked before in (Development) so how can i work with Stripe in production with Heroku -
Django REST Framework Depth Only For Specified Fields
So I have a Django REST Framework Serializer. Now I added a serializer for my Blog Posts, but I want the Serializer depth only for a specified field. Until now I get this: This is my serializer: class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = Job fields = ["postid", "title", "description", "slug", "tag", "views", "user", "release_date", "city", "country"] depth = 1 And this is the wrong output { "results": [ { "postid": 1, "title": "Test Title", "slug": "test-title", "description": "Test Description", "tag": { "tagid": 1, "tagname": "school" }, "views": 15, "release_date": "2021-05-25T17:15:22.223311Z", "user": { "userid": 1, "password": "pbkdf2_sha256$216000$drVQlm6CdO+g90ygM3gXFUHBb+ctaKDA=", "username": "user1", "email": "testemail@gmail.com", "posts": 0, "date_joined": "2021-05-25T17:13:29.865119Z", "last_login": "2021-05-25T17:14:12.808671Z", "is_admin": true, "is_active": true, "is_staff": true, "is_superuser": true }, "city": "New York", "country": { "countryid": 1, "continent": "america", "countryname": "usa", "currency": "$", "symbol": "US" } }, ... ] } But the problem is, I only want the depth for tag and country, not for user :/ Like this: { "results": [ { "postid": 1, "title": "Test Title", "slug": "test-title", "description": "Test Description", "tag": { "tagid": 1, "tagname": "school" }, "views": 15, "release_date": "2021-05-25T17:15:22.223311Z", "user": 1, "city": "New York", "country": { "countryid": 1, "continent": "america", "countryname": "usa", "currency": "$", "symbol": "US" } }, ... ] … -
Multiplication of SQL queries for one django objects.get request
I'm working on Django, an I have a ClientPartner class as Model : class ClientPartner(BusinessObject): charge_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_charge") client_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_client") legal_entity = models.ForeignKey("legal_entity.LegalEntity", on_delete=models.CASCADE, related_name="partners") partner = models.ForeignKey("legal_entity.LegalEntity", on_delete=models.CASCADE, related_name="client_legal_entities") product_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_product") vendor_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_vendor") and I query the table as shown below : lo_partnership = ClientPartner.objects.get(legal_entity=self.owner, partner=io_vendor) I use django standard logs and when I run this line I have the SQL queries below : DEBUG 2021-05-27 21:38:42,237 utils 21776 22144 (0.016) SELECT "client_clientpartner"."id", "client_clientpartner"."creation_date", "client_clientpartner"."creation_user_id", "client_clientpartner"."deleted", "client_clientpartner"."deletion_date", "client_clientpartner"."deletion_user_id", "client_clientpartner"."update_date", "client_clientpartner"."update_user_id", "client_clientpartner"."charge_account_id", "client_clientpartner"."client_account_id", "client_clientpartner"."legal_entity_id", "client_clientpartner"."partner_id", "client_clientpartner"."product_account_id", "client_clientpartner"."vendor_account_id" FROM "client_clientpartner" WHERE ("client_clientpartner"."legal_entity_id" = 2 AND "client_clientpartner"."partner_id" = 935) LIMIT 21; args=(2, 935) DEBUG 2021-05-27 21:38:42,243 utils 21776 22144 (0.000) SELECT "legal_entity_legalentity"."id", "legal_entity_legalentity"."creation_date", "legal_entity_legalentity"."creation_user_id", "legal_entity_legalentity"."deleted", "legal_entity_legalentity"."deletion_date", "legal_entity_legalentity"."deletion_user_id", "legal_entity_legalentity"."update_date", "legal_entity_legalentity"."update_user_id", "legal_entity_legalentity"."comment", "legal_entity_legalentity"."image_id" FROM "legal_entity_legalentity" WHERE "legal_entity_legalentity"."id" = 2 LIMIT 21; args=(2,) DEBUG 2021-05-27 21:38:42,248 utils 21776 22144 (0.000) SELECT "legal_entity_legalentity"."id", "legal_entity_legalentity"."creation_date", "legal_entity_legalentity"."creation_user_id", "legal_entity_legalentity"."deleted", "legal_entity_legalentity"."deletion_date", "legal_entity_legalentity"."deletion_user_id", "legal_entity_legalentity"."update_date", "legal_entity_legalentity"."update_user_id", "legal_entity_legalentity"."comment", "legal_entity_legalentity"."image_id", "legal_entity_organization"."legalentity_ptr_id", "legal_entity_organization"."accounting_method_id", "legal_entity_organization"."ape", "legal_entity_organization"."bic", "legal_entity_organization"."commercial_name", "legal_entity_organization"."country_id", "legal_entity_organization"."draft", "legal_entity_organization"."factory_code", "legal_entity_organization"."legal_form_id", "legal_entity_organization"."main_activity_id", "legal_entity_organization"."name", "legal_entity_organization"."siren", "legal_entity_organization"."tax_model_id", "legal_entity_organization"."url_login", "legal_entity_organization"."url_privacy", "legal_entity_organization"."url_website", "legal_entity_organization"."vat_number", "legal_entity_organization"."vat_regime_id" FROM "legal_entity_organization" INNER JOIN "legal_entity_legalentity" ON ("legal_entity_organization"."legalentity_ptr_id" = "legal_entity_legalentity"."id") WHERE "legal_entity_organization"."legalentity_ptr_id" = 2 LIMIT 21; args=(2,) DEBUG … -
How to add event to LeafletWidget in django-leaflet?
In my django app I have a Worker model with a name and location (Point). Using django-leflet LeafletWidget I can create a Form where the user can set a location (marker to that worker). Is it possible to add an event to the widget, so, every time the user sets the marker, or change the marker position it gets the coordinates of that point and perform other actions (like an ajax request)? class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'location': LeafletWidget(), } in the template i just call 'forms.location' and it renders the map with the controls to set a marker Every time the user sets the marker I want to get the location of that marker. How do I do that? -
Django form only takes user registration only as a whole
I'm trying to create a registration form using the django.auth but when try to submit the form it doesn't work if i specify forms.username, forms.email etc. only if i use {{form}} as a whole. like if i have <form method="POST" class='form-group'> {%csrf_token%} <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1"><i class="fa fa-user"></i></span> {{form.username}} </div> <button type="submit" class="btn btn-success">Register</button> </form> instead of using <form method="POST" class='form-group'> {%csrf_token%} {{form}} <button type="submit" class="btn btn-success">Register</button> </form> it doesn't work, it doesn't submit and i can't find the new user in admin django/users. -
could not translate host name "db" to address: Name or service not known - Heroku via Docker
I know there is a lot of this floating around, but their answers does not seem to apply to my case. I'm deploying a gis web application from docker to heroku. I am encountering this problem when I run heroku run python manage.py migrate I have this line in my settings.py import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES.update(default=db_from_env) This is my docker-compose-prod.yml db: image: kartoza/postgis:13.0 volumes: - postgis-data:/var/lib/postgresql environment: - POSTGRES_DB=gis - POSTGRES_USER=foo - POSTGRES_PASS=bar - ALLOW_IP_RANGE=0.0.0.0/0 - POSTGRES_MULTIPLE_EXTENSIONS=postgis,hstore,postgis_topology,postgis_raster,pgrouting I used the build package https://github.com/cyberdelia/heroku-geo-buildpack.git and also manually changed the DATABASE_URL to heroku config:add DATABASE_URL=postgis://foo:bar@db:5432/gis Isn't db_from_env automatically points to kartoza/postgis:13.0? Why is this happening here.