Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to shuffle/randomize list items after regrouping them using Django's regroup template tag
I have this list presented in dictionaries: cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}, {'name': 'New York', 'population': '20,000,000', 'country': 'USA'}, {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, ] I have regrouped the list using Django's regroup tag: {% regroup cities by country as country_list %} <ul> {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for city in country.list %} <li>{{ city.name }}: {{ city.population }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> This is the template output: India Mumbai: 19,000,000 Calcutta: 15,000,000 USA New York: 20,000,000 Chicago: 7,000,000 Japan Tokyo: 33,000,000 That is pretty much of what I intended to do. I now want to randomly shuffle items under each country list. For example, under USA, I want to shuffle New York and Chicago so that the display is not biased to the viewer. When I use shuffle(cities) in my views, I get an output like this: India Mumbai: 19,000,000 USA New York: 20,000,000 India Calcutta: 15,000,000 USA Chicago: 7,000,000 Japan Tokyo: 33,000,000 I basically want to shuffle cities while remaining intact under their countries. I dont want the position of … -
Chnaging the DATABASE_URL in heroku
So i tried to deploy my django app to heroku and used the heroku postgres as the database. But the problem was that i have to use postgis and to do that, we need to change the postgres to postgis in the DATABASE_URL. But in heroku we cannot change it as it gives the error; attachment values cannot be changed. So i came up with a solution. I removed the heroku-postgres from my main app and create another app, created heroku-postgres there and then took the url of that other app and used that as the value of DATABASE_URL in my main app. Now i can easily update that as that is not attached with my main app and that worked perfectly. Now the problem is that, is it necessary to have db attached because heroku says; Please note that these credentials are not permanent. Heroku rotates credentials periodically and updates applications where this database is attached. Credentials mentioned above are the database credentials. So if the creds change, my app will not work but i cannot attach the db with my main app, as the url will be stored as a new env variable which will be of no … -
Django ORM for sum with group by
I have a database table consisting of scores for students on individual courses they took over the years. And I am trying to get the sum of scores for each student. How can I achieve this using Django ORM? The query that I used is qs = Enrollment.objects.filter( semester__gte=start, semester__lte=last, course__teacher__teacher=request.user ).values('student_id').annotate(total=Sum('score')) And the result produced is like this id student_id course_id semester score grade status comments total 0 2 2 1 1 87 B Passed 87 1 3 2 3 1 97 A Passed 97 2 6 8 1 1 84 B Passed 84 3 7 8 3 1 65 D Passed 65 4 9 7 3 1 88 B Passed 88 5 11 7 1 1 79 C Passed 79 From this, how can I derive this? student_id total 2 184 8 149 7 167 -
Django Channels ValueError: No route found for path
I follow this tutorial to build a chat system https://channels.readthedocs.io/en/stable/tutorial/part_1.html It works fine when the room name is a string without white spaces, say "Room1". WebSocket HANDSHAKING /ws/chat/Room1/ WebSocket CONNECT /ws/chat/Room1/ However, when I change the room name to "Room 1", it results in WebSocket HANDSHAKING /ws/chat/Room%201/ [127.0.0.1:59947] Exception inside application: No route found for path 'ws/chat/Room 1/'. ValueError: No route found for path 'ws/chat/Room 1/'. I have tried to change the roomname by replacing the white space with "%20" in the HTML, routing.py and consumers.py. None of them works. How can I solve this problem? -
Djnago:How to generate a pdf file
i want to generate a pdf file containing the OCR result of an uploaded image, but i can't seem to figure out how. when i store the result in a txt file it works but every pdf i create is corrupted. i used FPDF to create the pdf but it's not working. if self.id : #this here to see if there is an image upload in order to generate the file c=''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) file=(ContentFile(Create_Pdf(self.image),name='file.pdf')) pdf = FPDF(format="A4") pdf.add_page() pdf.set_font("Arial", size=12) for x in file.readlines(): pdf.cell(0,7, txt=x, ln=1) res=pdf.output("Data.pdf") File.objects.create( file=(ContentFile(res,name='file.pdf') )) -
Can I develop live video streaming website using django?
If yes then what should I need to know before starting, please specify I'm trying to build a Live video and text Streaming Application (Web & Mobile) Through my search, I found the Gevent-socketio library, but it is old and I did not find a suitable explanation to start with -
How to include images kept in static folder in JavaScript as variables in Django
how to do the image part here I'm getting my data from a JSON data list. I can't figure out how to include those image sources from the data inside the JavaScript ${variable} notation like others variables as shown in the figure. The images are kept in the static folder -
How to use an email URL with a password which contains slash character of `/`
For a Django app, I'm trying to set environment variable EMAIL_URL to smtp://username:password@email-smtp.us-east-1.amazonaws.com:587/?tls=True where password contains slash character of /. Amazon SES is giving me a password which contains / character for some reason. For example: export EMAIL_URL="smtp://AKIAYZT73XCKGD:BFB6UvkMgn9dniEGQZc/xM/KDS9Agc/S2@email-smtp.us-east-2.amazonaws.com:587/?tls=True" And then running: python3.9 manage.py runserver But I'm receiving an error: ValueError: Port could not be cast to integer value as 'BFB6UvkMgn9dniEGQZc' Error is thrown at this file: myapp-venv/lib/python3.9/site-packages/dj_email_url.py At 'EMAIL_PORT': url.port, statement of this function: def parse(url): """Parses an email URL.""" conf = {} url = urllib.parse.urlparse(url) qs = urllib.parse.parse_qs(url.query) # Remove query strings path = url.path[1:] path = path.split('?', 2)[0] # Update with environment configuration conf.update({ 'EMAIL_FILE_PATH': path, 'EMAIL_HOST_USER': unquote(url.username), 'EMAIL_HOST_PASSWORD': unquote(url.password), 'EMAIL_HOST': url.hostname, 'EMAIL_PORT': url.port, 'EMAIL_USE_SSL': False, 'EMAIL_USE_TLS': False, }) if url.scheme in SCHEMES: conf['EMAIL_BACKEND'] = SCHEMES[url.scheme] # ... return conf Tried I tried to escape the / with \ but it didn't work! -
Django receives incomplete POST data
I am posting json-formatted data to the backend written with Django 3.1.2. However, the data does not seem to received correctly. js code: var httpRequest = new XMLHttpRequest(); httpRequest.open("POST", "http://" + window.location.host + "/upload/", true); httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); httpRequest.send(encodeURI("data=" + json); httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { console.log("Done!"); } Django: data = request.POST.get('data') f = open('data.txt', 'w+') f.write(data) f.close() The data written in the file is incomplete. Nor is it complete when I try to print it. What might be the problem? Is it because the json string I post is too long? -
Django Rest Framework: Disable save in update
It is my first question here, after reading the similar questions I did not find what I need, thanks for your help. I am creating a fairly simple API but I want to use best practices at the security level. Requirement: There is a table in SQL Server with +5 million records that I should ONLY allow READ (all fields) and UPDATE (one field). This is so that a data scientist consumes data from this table and through a predictive model (I think) can assign a value to each record. For this I mainly need 2 things: That only one field is updated despite sending all the fields of the table in the Json (I think I have achieved it with my serializer). And, where I have problems, is in disabling the creation of new records when updating one that does not exist. I am using an UpdateAPIView to allow trying to allow a bulk update using a json like this (subrrogate_key is in my table and I use lookup_field to: [ { "subrrogate_key": "A1", "class": "A" }, { "subrrogate_key": "A2", "class": "B" }, { "subrrogate_key": "A3", "class": "C" }, ] When using the partial_update methods use update and this … -
Get ids of many to many table
in django if there's table with many to many field like that : class Category(models.Model): name = models.CharField(unique=True, max_length=255) icon = models.ImageField(upload_to='images') sport = models.ManyToManyField(Sport) when you try to get all objects from this table you do this : Category.objects.all() and the result will be like that after serializing : "data": [ { "id": 1, "name": '..' "icon": '...' "sport": [ 1, 2 ] ] } so my question here how to achieve the same result using pure sql I tried this : sql = '''select a.*,b.sport_id,array_agg(b.sport_id) as sport from category a join category_sport b on b.category_id=a.id group by a.id,b.sport_id ;''' but the result was like that : "data": [ { "id": 1, "name": '..' "icon": '...' "sport": [ 1, ] }, { "id": 1, "name": '..' "icon": '...' "sport": [ 2 ] ] } -
every-time i use .update(release_time=initial_time) i get an error 'int' object is not iterable but if i changed it to .all() it work out just fine
here is my code : def release_it(request, id): if request.method == "POST": x = Lap.objects.get(pk=id) x.released = True p = request.POST["release_time"] initial_time = datetime.strptime(p, '%Y-%m-%dT%H:%M') x.release_time = initial_time x.save() load = Loaded.objects.filter(lap=id).update(release_time=initial_time) for l in load: l.save() return render(request, "race/index.html", { "message":"released!", "x":x, "load":load }) return render(request, "race/index.html", { "message":"released!" }) i get this error File "/Volumes/John HDD/Visual Studio Code /CS50-web-Programming-with-Python-and-JavaScript/Project/pigeon_race/race/views.py", line 27, in release_it for l in load: TypeError: 'int' object is not iterable but when i replace load = Loaded.objects.filter(lap=id).all(). it work just fine here is my model class Loaded(models.Model): race_id = models.CharField(max_length=64) lap = models.CharField(max_length=64) lap_name = models.CharField(max_length=64) pigeon_id = models.CharField(max_length=65) pigeon_name = models.CharField(max_length=64) pigeon_ring = models.CharField(max_length=64, blank=True) pigeon_hcode = models.CharField(blank=True, max_length=64) release_time = models.CharField(blank=True, max_length=64) clock_time = models.CharField(blank=True, max_length=64) -
Django Final/Landing Page
I am working on a Django based server and i take some attachments from the user and process it in this function def get_request(request): df = pd.DataFrame() flag = 0 # if this is a POST request we need to process the form data if request.method == 'POST': #Processing and generating results return render(request, 'result.html', {'data': to_send, 'file': df, 'flag': flag}) Initially, I wanted to render the results HTML page as above but instead I decided to send an email containing the results and send it to the user. I am able to send the results but I want to render a final page with some text while the results generate(might take some time depending on the size of the input). How can I do so without waiting for the processing to end and let it be in the background even if the user closes the tab? -
Django queryset filter with Q object or relationship is not working as expected
I have a model A with two fields: class A(models.Model): text = models.TextField() b = models.ForeignKey( B, null=True, blank=True, on_delete=models.SET_NULL ) And a model B: class B(models.Model): text = models.TextField() I have a record A with text field "12345" and a b field as null. When trying to filter model A with: queryset = queryset.filter( models.Q(text__icontains="123") | models.Q(b__text__icontains="123") ) But the record is filtered out. Did I miss anything? -
Django, CSVs, FileField and S3 - How to stream a CSV file into an S3 Bucket and also save it into a Django Model's FileField?
everyone. Hope you're doing well. I would like to start this question by prefacing that I'm a real newbie when it comes to AWS. Right now I'm working on a Django app with a friend that already has some more experience with web development and he had already set up everything in AWS that is, we have most of our files uploaded there, a staging app running and some other configs. I'm working on a backend implementation of transforming some database data from our web app into CSV files and uploading it into the cloud. Basically, we have an endpoint where a User can ask for data from another URL of the site, and our app will transform the data into a .CSV file, export it to S3 and AT THE SAME TIME saving it on a FileField of the model. Then, once the File is uploaded, the user will receive it in its e-mail. Since the file could be really big, the BIG question is: How do you stream .CSV file into a S3 Bucket and have Django save it into the FileField attribute of a model? Here's my code for reference (This is the only way it created … -
Django drops ListView and uses DetailView for a list object, then gives NoReverseMatch
PyCharm 2020.2 Python 3.9 Django 3.1 Ubuntu 20.04 LTS project urls.py: urlpatterns = [ path('', views.home, name='home'), path('admin/doc/', include('django.contrib.admindocs.urls')), path('admin/', admin.site.urls), path('ktab/', include('ktab.urls')), app.models.py: def get_absolute_url(self): return django.urls.reverse('EntryDetail_url', kwargs={"slug": self.slug}) app.urls.py: path('entry/index/', views.EntryIndex.as_view(), name='EntryIndex_url'), path('entry/list/', views.EntryList.as_view(), name='EntryList_url'), path('entry/<slug>:<title>/', views.EntryDetail.as_view(), name='EntryDetail_url'), app.views.py: class EntryIndex(ListView): model = Entry template_name = 'EntryList_.html' def get_context_object_name(self, object_list): return 'object' def get_queryset(self): return Entry.objects.all() def get_context_data(self, **kwargs): context = super(EntryIndex, self).get_context_data(**kwargs) context['searchbox'] = SearchBox() return context class EntryDetail(DetailView): model = Entry template_name = 'EntryDetail_.html' def get_context_data(self, **kwargs): context = super(EntryDetail, self).get_context_data(**kwargs) context['searchbox'] = SearchBox() return context class EntryList(ListView): model = Entry template_name = 'EntryList_.html' Error Message: NoReverseMatch at /ktab/entry/list/ Reverse for 'EntryDetail_url' with keyword arguments '{'slug': 'executive-summary-hattie-urls-and-views'}' not found. 1 pattern(s) tried: ['ktab/entry/(?P<slug>[^/]+):(?P<title>[^/]+)/$'] ...... In template /home/malikarumi/Projects/lifeandtimes/chronicle/templates/base_index.html, error at line 0 But of course, there’s nothing there at line zero but the DOCTYPE declaration. I am trying to call the index for this model’s objects, which is the same as a list. For reasons that I do not understand, and am tired of fighting with, it keeps trying to give me a single object on the detail template. The object 'executive-summary-hattie-urls-and-views' happens to be queryset[0]. You can see that I put entry/index and entry/list ahead of … -
Django - ModuleNotFoundError: No module named 'djangoformsetjs'
I have a new Django app, with the following module in my settings.py: INSTALLED_APPS = [ 'djangoformsetjs', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_hosts', 'rest_framework', 'djoser', 'app', # Enable the inner app 'phonenumber_field', ] When trying to make a first upload to Heroku, it returns the error : ModuleNotFoundError: No module named 'djangoformsetjs' Although it works fine locally. I tried re-installing from the terminal : pip install django-formset-js And everything seems fine : Requirement already satisfied: django-formset-js in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (0.5.0) Requirement already satisfied: django-jquery-js in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (from django-formset-js) (3.1.1) Requirement already satisfied: Django in /Users/homepc/.local/lib/python3.8/site-packages (from django-formset-js) (2.2) Requirement already satisfied: sqlparse in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (from Django->django-formset-js) (0.4.1) Requirement already satisfied: pytz in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (from Django->django-formset-js) (2020.1) Am i missing something in my setup please ? -
Django:: Cant update form
I have gone blind trying to figure this out... I have done everything correctly but for some reason I am unable to update a form. views.py def Mainpage(request): model = datas.objects.filter(qs_login='nicobari') context = {'items': model } return render(request,"main/auditform.html",context) def updateform(request, pk): model = datas.objects.filter(qs_login='nicobari') data= datas.objects.get(Task_ID=pk) form = auditForm(instance=data) if request.method == 'POST': form = auditForm(request.POST, instance=data) if form.is_valid(): form.save() context = { "items": model, "data": data } return render(request,"main/auditform.html", context) Everything works but when i try to click on : <input class="submit" type="submit" value="Submit"> It just refreshes the page but doesnt update the content. Could anyone help me understand what I could have done wrong? -
Delaying function in Django
I have the following button: <a href="/donations/{{donation.pk}}/delete/" onclick="showAlert" >Accept</a> The delete function: def deleteDonation(request, id=None): donation = get_object_or_404(Donation, pk=id) donation.delete() return redirect('/dashboard/') I also have a javascript function called onClick, which is triggered when my button is clicked. What I want: I want my program to call my javascript function, and wait a few seconds before the python function is called. How can I do this, I used time.sleep(5), but this only delayed the python function and did not call my javascript one. -
Customize register in django rest knox
How to make the user register with other fields like birth date besides the name and email, and how to do password confirmation? -
Error while loading website on Nginx & django
I had a server which is running django & Nginx. I had tried to install SSL certificate, but it seems that the certificate had been installed on apache. So, I had stopped Apache, and reboot the server, but I can't load the page. When I do netstat on nginx sites-enabled, then I see: tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 25609/nginx tcp6 0 0 :::80 :::* LISTEN 25609/nginx The result is for ports listening 9000 (which is django): tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 28178/python But the website is not running . How can I fix this? Thank you -
Where to serve files in deployment and production with django
I am in the process of building a website with Django. The web app is for a local store in my city. The store sells gardening courses and workshops (the store is my mom's btw). I want the admin of the page (the owner of the store) To be able to add new courses whenever she wants. So I made this model for the courses: class Curso(models.Model): title = models.TextField() photo = models.ImageField(upload_to='cursos/') description = models.TextField() price = models.IntegerField(null=False) content = models.JSONField(blank=True) clases = models.IntegerField(default=1) duration = models.IntegerField() isworkshop = models.BooleanField(default=False) I included an ImageField because in the fronted there should be an image related to the course. I added the path /cursos/ but I actually have no idea where the image is going. I saw people had a "media" folder. But I also read the "media" folder was only for images uploaded by the user? This is my static folder looks like: static |_app |_js |_css |_sass |_icons |_images |_homeslider |_plants |_pictures Should the images uploaded from the admins app in that same folder? Anyways I don't know where to store the images. And I don't have a hosting yet which leads me to my next question: What should … -
source.transform gives an error latitude or longitude exceeded limits
I get the following error when running this statement: Any suggestions on what might be going wrong This is the object details source : SRID=4326; POINT(-122.20874 47.68419) This is the statement: res = source.transform(32148, clone=True) The error is: GDAL_ERROR 1: b'latitude or longitude exceeded limits' Any suggestions on how I can fix this ? -
Extending ManyToManyField In Templates
I need to create a manytomany field that has some options and then next to each option there is an extra field My models: class Subject(models.Model): name = models.CharField(max_length=30) duration = models.IntegerField() price = models.IntegerField() class Student(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) subject = models.ManyToManyField(Subject,through="StudentSubject") class StudentSubject(models.Model) student = models.ForeignKey(Student,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) discount = models.IntegerField() I used the intermediate model StudentSubject(this contains the extra field) but I'm not sure how I should render this in a template I want to do something like this: Math DiscountField1 Physics DiscountField2 CompSci DiscountField3 -
How to return a custom validation error message ins django-enumchoicefield?
I am using django-enumchoicefield and I want to return a custom Validation Error instead of default Key Error if api receives incorrect value for model. class SexChoices(ChoiceEnum): male = "male" female = "female" class CandidateModel(models.Model): id = models.CharField(primary_key=True, max_length=20) name = models.CharField(max_length=50) sex = EnumChoiceField(enum_class=SexChoices) I have tried validators=[some_validator] in EnumChoiceField() but its not working. Also, if I define a custom model manager class for CandidateModel it still giving KeyError instead of Validation Error