Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.utils.datastructures.MultiValueDictKeyError: 'file' on passing a URL
I have a form which contains a file upload but I am not uploading file through that, I store it into firebase storage then pass the URL through ajax request. In my views.py I got -: if request.method == 'POST': title = request.POST['title'] time = request.POST['time'] description = request.POST['description'] file_URL = request.POST['file_URL'] date = request.POST['date'] The error occurs on file_URL = request.POST['file_URL'] As it says django.utils.datastructures.MultiValueDictKeyError: 'file_URL' In my template I have a very simple form - <form id="create-assignment"> {% csrf_token %} <div class="title-time-wrapper"> <input type="text" name="assignment-title" id="assignment-title-input" required class="assignment-form-input" placeholder="Title" autocomplete="off"> <input type="text" name="assignment-time" class="assignment-form-input" id="assignment-time-input" required placeholder="Time" autocomplete="off"> </div> <textarea rows="5" cols="40" name="progress" id="assignment-description-input" required class="assignment-form-input" placeholder="Description" autocomplete="off"></textarea> <input type="file" name="files[]" id="assignment-file-input"> <input type="submit" class="submit-btn" value="Save" id="assignment-form-submit"> </form> And finally for my Javascript -: var file, file_URL var storage = firebase.storage(); var storageref = storage.ref('Assignments').child('test'); $(document).on('submit', '#create-assignment', function(e){ let today = new Date().toISOString().slice(0, 10) file = document.getElementById("assignment-file-input").files[0]; var thisref=storageref.child(file.name).put(file); thisref.on('state_changed',function(snapshot) { console.log('Done'); }, function(error) { console.log('Error',error); }, function() { // Uploaded completed successfully, now we can get the download URL thisref.snapshot.ref.getDownloadURL().then(function(downloadURL) { file_URL = downloadURL; }); }); e.preventDefault(); $.ajax({ type: 'POST', url: '/teacher/exam/create/', data:{ title: $('#assignment-title-input').val(), time: $('#assignment-time-input').val(), description: $('#assignment-description-input').val(), fileURL: file_URL, date: today, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() } }); … -
Is it possible to create new HTML files programmatically with Django?
As the title indicates, I want to know if it is even possible to do this. I want to run a function in my Django app that creates a new file; for example, say I have a templates folder, and within it I have two files: file_1.html and file_2.html. Upon running my function, I now want the folder to contain a third file, file_3.html. Is this possible? If so, how can I go about doing this? Any help is appreciated! -
DB table design
I'm creating a Django application using PostgreSQL and have a question on how to design my tables. I'm create a database that will hold YuGiOh monsters. Monsters are varied in their definition and are often combined and twister together. For example, here are three different types: Xyz Synchro Fusion Pendulum For the majority, a monster with be one of the three above. However, sometimes it can be two (and more). For all, except Pendlulum, would hold the same fields. However, Pendulum monsters would require three additional columns. Initially I was going to create one big table and allow fields to be null but I would have to implement custom logic to ensure fields cannot be checked (e.g. accidentally monster a non-pendulum a pendulum monster). Here is my implementation: I've created a base monster table that holds all things common in every Monster card. I've created a table for each different type of monster card (Pendulum, Xyz, etc.) that uses a foreign key to the base monster table, and added additional columns respectively. My reasons for the design are: If they want to search a particular card (e.g. Xyz) they would only search that table. If a monster is indeed two … -
Django with postgresql, the datetime microsecond's leading 0 is disappeared
I'm trying to retrieve datetime typed data from postgresql on django. But if the microsecond has leading 0, like below | datetime_field | |2021-06-07 09:22:13.099866+00 | the result is shown as datetime.datetime(2021, 6, 7, 9, 22, 13, 998660, tzinfo=<UTC>) in Python. Take notice of microsecond 099866. It has been changed to 998660. If I insert the resulted datetime object without any change to postgresql, it is uploaded as below. | datetime_field | | 2021-06-07 09:22:13.99866+00 | The 0 at the head is disappeared. It seems this problem is derived from psycopg2, not just django but I can't find any resolution for this. How can I get the microseconds in its entierty? p.s. Welcome for editing for just the English. As I'm not an English speaker, I'm not sure whether I wrote correct expressions. -
Setting to submit data from HTML of textarea in view.py in Django and set as temporary data
Background of the project: I am working on a text-to-speech (TTS) converter with Django. I have the python code that works well for the TTS converting and output the audio file, but I want to make it as a web app and gonna deploy to the cloud, that's why I am plugging it to Django. There are only two variables that input from the user: the text content that would be converted and selected language. My thought is to set the input variables as temporary items so that it wouldn't bomb the server - so to the output file to save as temporary file and automatically download to the user and delete the file after finish downloading. After searching for possible similar cases and solution, I found a post which is explaining how to use in memory and temporary files, but it seems only for uploading files. My question is, right now I am coding to send the data to the sqlite3 database but obviously it doesn't make sense to input data and then delete frequently. I am thinking to use session with the view.py as follow (not sure if it works): from django.shortcuts import render from django.http import HttpResponse … -
should I remove duplicate pagnate methods in Django model reported by Sonarqube?
I am working on a Django project which defines lots of models and some of them have "paginate" method. Quite a few of these paginate methods are exactly the same. Sonarqube reported them as duplicated blocks. Should the code be refactor so there is only one paginate method for these models? If yes, how? If not, how to tell which "duplicates" should be fixed and which should not be? -
AttributeError when attempting to save a file downloaded from requests
I am trying to save MP3 media files as they are packaged in a requests response to local storage. I've defined a model MP3, with its corresponding manager, MP3Manager. In the manager, we have a class method used for obtaining the data, ideally from the local database, but from an external media server if not present. This retrieval occurs in a class method called get_mp3(). Inside get_mp3(), we also have save_mp3(), which is meant to take the bytes string from response.content, save it to the filesystem, and create a database entry. However, there appears to be some kind of formatting issue, because I get the following error while executing the save_mp3() return statement: AttributeError: '_io.BufferedWriter' object has no attribute '_committed' How do I resolve this? Entire mp3.py file here: import os import requests from django.db import models from django.utils.translation import gettext_lazy as _ from rest_framework import status from rest_framework.exceptions import NotFound from api.exceptions import InternalServerError from api.models import TimestampedModel class MP3Manager(models.Manager): """ Class defining utility methods for downloading MP3 pronunciation audio files from the Merriam-Webster media servers. """ @classmethod def get_mp3(cls, id, url): """ Obtains an MP3 file from local storage if a database entry exists, and downloads from the … -
How to make GROUP BY query with Many To Many Fields in Django
I want to make a request to select the number of total quantity per product. The models look like this: class Products(models.Model): name = models.CharField(max_length=200) class Orders(models.Model): product = models.ManyToManyField(Products, through='OrdersQuantities') class OrdersQuantities(models.Model): quantity = models.IntegerField() product = models.ForeignKey(Products, on_delete=models.DO_NOTHING) And the SQL query I want to make SELECT name, SUM(quantity) AS qte FROM products, ordersquantities WHERE ordersquantities.product_id = product.id GROUP BY name ORDER BY qte DESC Thank you for reading! -
Declaring Model Value in Django
I am pretty new to Django and I cannot figure out how to declare the value of a model. For example, if I have a CharField that takes the choice of three sizes s, m, l. Then auto-populate the value for length and width. So, it would be something like this. s = { "length": 5, "width": 7 } m = { "length": 8, "width": 10 } l = { "length": 12, "width": 18 } CHOICE_LIST = [ ("s", "Small"), ("m", "Medium"), ("l", "Large") ] size = models.CharField(choices = CHOICE_LIST) length = models.IntegerField() width = models.IntegerField() Then somehow make the model instances length and width = the dictionary length width based on model instances size. So, if you inputted small it would make length 5 and width 7. -
Django query only employees belonging to that company
I have 2 modules a module representing a company: class ExternalService(models.Model): # Fields company_name = models.CharField(max_length=60) address_street = models.CharField(max_length=60) address_postcode = models.CharField(max_length=30) address_city = models.CharField(max_length=30) company_telephone = models.CharField(max_length=30) company_email = models.CharField(max_length=60) company_support_telephone = models.CharField(max_length=30) company_support_email = models.CharField(max_length=30) company_website = models.URLField(null=True, blank=True) notes = models.TextField(max_length=448) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: pass def __str__(self): return str(self.company_name) def get_absolute_url(self): return reverse("asset_app_ExternalService_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_ExternalService_update", args=(self.pk,)) and a module representing employees: class ExternalServiceContact(models.Model): # Relationships company = models.ForeignKey("asset_app.ExternalService", on_delete=models.SET_NULL, blank=True, null=True) position = models.ForeignKey("asset_app.ExternalServicePosition", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=60) email = models.CharField(max_length=30) cellphone = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: pass def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_ExternalServiceContact_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_ExternalServiceContact_update", args=(self.pk,)) In my views.py I want to get all the employees belonging to that company. So when I look at my DetailView I only get listed employees beloning to that company. class ExternalServiceDetailView(generic.DetailView): model = models.ExternalService form_class = forms.ExternalServiceForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['employees'] = models.ExternalServiceContact.get(#######).order_by('name') return context just dont know what to insert into my get() -
Relation <Name> doesn't exist when using Model.objects.get() django
History: I have been using GNUCash for Accounting and it stores all customer information so to integrate Job Delivery of files and invoices i was integrating GNUCash database on Postgres with the existing local server to send and backup files and mark them automatically. So i did inspectdb> models.py and got all the models from gnucash database. Now 'Customers.objects.all()' is working file and gives list of all the data but 'Customers.objects.get()' doesn't work and gives error. View: def get_job_list(client_id): try: client = Customers.objects.get(id = client_id).using('gnucash') print(client) ###job_list = Jobs.objects.get(owner_guid = client.guid,active = 0).using('gnucash') except Exception as e: job_list = None return job_list Error: The above error states that the table doesn't exist customers. But when i change the code to Model.objects.all() it works fine. View: def get_job_list(client_id): try: client = Customers.objects.all().using('gnucash') #This is Changed print(client) job_list = None ###job_list = Jobs.objects.get(owner_guid = client.guid,active = 0).using('gnucash') except Exception as e: job_list = None return job_list Output: I looked at This question which focuses on lowecase table name which is correct for me as .all() work but not .get(). Here is model if you want to take a look: class Customers(models.Model): guid = models.CharField(primary_key=True, max_length=32) name = models.CharField(max_length=2048) id = models.CharField(max_length=2048) notes … -
Sending emails in Django with NameCheap email account
I set up an email account with NameCheap that I use with my Django app. Below is my email configuration based on information provided by NameCheap EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'news@mydomain.com' EMAIL_HOST_PASSWORD = os.getenv('EMAIL_PASSWORD') EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = 'WebsiteTitle <news@mydomain.com>' Now when I use send_mail() django function (eg. after registration) it is like playing roulette - one time it works properly and sends out an email, another time it throws an error saying SMTPServerDisconnected at /reset-password/ Connection unexpectedly closed As if something was wrong with my email configuration. Do you have any idea what might cause it or how to try to fix it or debug it? Is it more likely NameCheap or Django? -
Page not found (404) “\media\actvites.png” does not exist Raised by: django.views.static.serve
Raised by: django.views.static.serve did anyone solve this?? -
Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ The current path, hello/, didn’t match any of thes
I am new to using Django and following a tutorial (https://video.cs50.io/w8q0C-C1js4?screen=gytX_rSwZRQ&start=1160). So far this course has been great! However, now I am stuck at successfully creating a new app using Django. Here is the result of my efforts: Django page not found Here is what the result should be: Hello, World page when found tutorial As far as I know I've done everything correctly, perhaps I am missing something? Below is the code I am using, which results in Django returning the error in the title: urls.py lecture3: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")) ] urls.py hello: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index") ] views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return HttpResponse("Hello, World!") settings.py: INSTALLED_APPS = [ 'hello', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I am currently using: Python 3.9.4, and Django 3.2.3 Any and all help that can be provided will be greatly appreciated. Thanks in advance, Richardson -
How to fetch object with multiple levels of reverse lookup
In my project, there are three models: class Level1(models.Model): name = models.CharField(max_length=250) class Level2(models.Model): name = models.CharField(max_length=250) level1 = models.ForeignKey(Level1, on_delete=models.RESTRICT) class Level3(models.Model): name = models.CharField(max_length=250) level2 = models.ForeignKey(Level2, on_delete=models.RESTRICT) Level1 model has 2 objects WA, TX. Level2 has 5 objects AAA, BBB where foreign key is WA and AAA, CCC, DDD where foreign key is TX. In Level3, I want to add a object RRRR where the Level2 foreign key object is AAA. When I tried to fetch the level2 by Level2.objects.get(name='AAA'), it shows error "get() returned more than one Level2 -- it returned 2!" How to solve this issue. Thanks in advance. -
Updating docker compose container properly?
Every time I run these commands that add new packages to my container and re-compose it, **problem ** : docker act like it compose the container again and it is not existed before, goalg: I need a way to just apply new the updates without rerun the docker file again and again. $ docker exec -it my_container bash $ root# pip install new_package $ root# pip freeze > requirements.txt then in my machine terminal $ docker-compose up -
DjangoFilterBackend filter in nested JSON filed
I have following structure: { "some_data": 123, "additionak_info": { "social_media": { "Tiktok": "true", "Instagram": "true" } } } with given list view class PersonListView(generics.ListAPIView): serializer_class = AllPersonSerializer permission_class = permissions.IsAuthenticatedOrReadOnly filter_backends = (DjangoFilterBackend, SearchFilter) search_fields = ['name'] filterset_fields = { 'some_data': ['exact'] } That i basically want to do is filter my result based on json value, something like mydomain/persons/all?additiona_info__social_media__Tiktok=true Does DjangoFilterBackend allows it from the box or i should implement kinda custom method? -
Filter data between two dates - Django
I'm trying to obtain data using django filter and connected to postgres database. The filter statement leads to error- 'ValueError: too many values to unpack (expected 2)' Here is the sql equivalent and my attempt at creating a django filter query You would notice that I have used two columns for storing datetime, review_time_datetime and match_time_datetime SQL Equivalent QUERY SELECT * FROM "table1" where review_time_datetime >'2021-06-14 00:00' and match_time_datetime < '2021-06-14 24:00' Django Filter QUERY filter_query = table1.objects.filter(review_time_datetime, match_time_datetime) -
Ordering the contents of a Django filter dropdown control
I have a Django filter, which works as expected allowing filtering of a List by selecting items in a dropdown control, but when it is rendered, the dropdown control items are in the order they were entered into the database, which is also to be expected. However, this is not user friendly as it's really difficult to find the desired item. I'm trying to figure out how to sort the list of items displayed in the dropdown control (composer) in alpha order. Any help would be appreciated as I'm a novice with all of this. The Filter code is below. I think I may need to manipulate a widget but not sure... class PieceFilter(django_filters.FilterSet): class Meta: model = Piece fields = ['composer', 'instrumentation'] exclude = ['title', 'description', 'study_notes', 'score_file', 'purchase_from', 'genre'] The filter renders two dropdown controls for filtering: 'composer' (which needs to be in alpha order) and 'instrumentation'. On the template, the following code renders a button to search on the chosen items from the dropdown controls. <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> The view being used: def library(request): pieces = Piece.objects.all().order_by('composer__name', 'instrumentation') p = Paginator(pieces, 10) print('NUMBER OF PAGES') print(p.num_pages) page_num = request.GET.get('page', 1) try: page … -
can i integrate chatbot with excel to fetch data and retrieve instead of sql database.?
I am new to programming just had a doubt while reading about bot. is it possible to integrate with excel sheets which have lots of items and its prices, if a user asks about a item in that table the bot reply with the price and the item is available or not? is it possible to create a bot using python? thank you -
Right Approach to Deploy Two Django App in Apache httpd server?
I have a Two Django Application which is created using python 3.8.x and python 3.9.x version. Now I need to deploy both apps in apache server in the same system in windows machine. and iam using mod_wsgi version 4.8.0 I Tried some things like settings two different instance of apache as well as listening to two different ports in single apache server and the error iam getting is Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38' sys.base_exec_prefix = 'C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38' sys.executable = 'C:\\Apache\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\Goku\\AppData\\Local\\Programs\\Python\\Python38' sys.exec_prefix = 'C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38' sys.path = [ 'C:\\Users\\Goku\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', '.\\DLLs', '.\\lib', 'C:\\Apache\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' -
How can I connect my Django application to AWS Elasticsearch?
I'm trying to use django-elasticsearch-dsl to connect my Django app to AWS Elasticsearch. I went through the documentation at https://django-elasticsearch-dsl.readthedocs.io/en/latest/, but all I found was how to connect to Elasticsearch on localhost. ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } What configuration do I have to add to connect my Django application to AWS Elasticsearch? -
Django + Postgres: saving PDF file with NUL (0x00) characters to DB and decoding it back to PDF
I have a pdf file that I want to save in my Postgres DB When I tried to save the file it brings A string literal cannot contain NUL (0x00) characters. so I followed the solution from here which replaces the null with a � character unicode(ppbData[0], errors='ignore').replace("\x00", "\uFFFD") The problem is that I can't convert it back to PDF now. I tried encode() and other methods file = open('new.pdf', 'wb') file.write(text.encode()) file.close() but it returns blank pdf Is there any way to replaces the � character with a null or any other way to convert it back to normal pdf? Maybe the first solution with replacing also wasn't right and there is another way? -
Django - NoReverseMatch Error (Views don't make any sense)
Django is the worst web framework I've ever used. def io_simulation(request): form = SimForm(request.POST) print('FIRST' + str(request.POST)) if form.is_valid(): form.save() print(form) return render(request, 'App/simulation.html', {'title': 'Simulation'}) This shows that my POST data is being sent correctly, but it's not reaching my database. FIRST<QueryDict: {'csrfmiddlewaretoken': ['dzowQoB3lk2IOOc19QXQDPZ3soJaxglaP76cURfjB6GMU3VBkHDe7IDhIp2CPpyK'], 'sim_concentration_range': ['3'], 'sim_concentration_range_2': ['4'], 'sim_concentration_range_unit': ['ppm']}> If I use io_simulation as the action for my form submission then I get a NoReverseMatch error that I don't understand, and I don't get my POST data printed out. If I use this completely nonsensical function as the action: def save_sim_data(request): print('SECOND'+str(request.POST)) if request.method == 'POST': request.POST.get('sim_concentration_range') request.POST.get('sim_concentration_range_2') request.POST.get('sim_concentration_range_unit') data=Sim() data.sim_concentration_range = request.POST.get('sim_concentration_range') data.sim_concentration_range_2 = request.POST.get('sim_concentration_range_2') data.sim_concentration_range_unit = request.POST.get('sim_concentration_range_unit') data.save() print('1') return render(request, 'nowhere.html') else: print('2') return render(request,'I/can/put/whatever I want here without any eRRerrors.html') Then I do see my POST data get printed (and it's correct (output in blockquote above)), but I still get nothing in my database. I cannot make any sense of Django debugging. What the hell is going on??? -
Why subclassing AppConfig is required in Django
From Django official docs, it reads: It is important to understand that a Django application is a set of code that interacts with various parts of the framework. There’s no such thing as an Application object. However, there’s a few places where Django needs to interact with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains metadata in an AppConfig instance for each installed application. Above means subclassing AppConfig is for maintaining metadata, which is used for configuration and also for introspection. Q1: Apart from labeling in Django Admin portal, I did not see any other use cases. any other examples for configuration and also for introspection ? Below posts did not help me out. What is the purpose of apps.py in Django 1.9? How is Django apps.py supposed to be used?