Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: no module named <projectname> while trying to get Django on Heroku?
Help PLEASE!!! Newbie trying to put Django on Heroku... ~8-( I am trying to set up a Django site on Heroku free tier. It works locally (using Sqlite3) and I got it working on Azure - but after following many howtos for this I cannot get it to work and have found no answers that solve this. I think I have followed all the tutorials guidance and I suspect it is my project/app structure and it can be solved with a tweak to my Procfile directive via some sort of pathing (based on other SO posts) - but cannot find definitive guidance on that. Heroku was set up with the same name as used in Git and is correct in wsgi.py. I have the requirements.txt(below), .gitignore, Procfile (web: gunicorn animalproject.wsgi --log-file -), .env ('DATABASE_URL=sqlite:///db.sqlite3' - just for local and this is in .gitignore) , runtime.txt (python-3.7.10), django-heroku, and settings.py correct I thought...But keep getting "ModuleNotFoundError: No module named 'animalproject'. I did install Postgresql per various tutorials and it shows as correct in Heroku. I am trying to use dj-database-url. I have not done a makemgrations/migrate yet. THANKS FOR ANY INSIGHTS!!! Here is my logs tail: 2021-06-15T23:34:14.819386+00:00 app[web.1]: [2021-06-15 23:34:14 +0000] … -
Omit pipenv virtual enviorment when using coverage
Okay, I'm using coverage to create unit testing in my Django project. I want to know what to add to omit the virtual environments. -
Edit images inserted by a formset
I have two models, one Called Asset and it contains a lot of fields, the other is the Asset Images they are related with a Foreign Key like this: class AssetImages(models.Model): image = models.ImageField(upload_to="asset_images/", default="") asset = models.ForeignKey(Asset, on_delete=models.CASCADE) Now adding the images with the following view function works perfectly: def add_view(request): ImageFormSet = modelformset_factory(AssetImages, form=ImageForm, extra=4) if request.method == "POST": formset = ImageFormSet( request.POST, request.FILES, queryset=AssetImages.objects.none() ) Addform = AddPropertyForm( request.POST, request.FILES, error_class=DivErrorList, ) if Addform.is_valid() and formset.is_valid(): property_form = Addform.save(commit=False) property_form.save() for form in formset.cleaned_data: if form: image = form["image"] photo = AssetImages(asset=property_form, image=image) photo.save() messages.success( request, "Thanks! your property has been added successfully" ) else: print("errrrrrrrrrrrrrrrrror") print(Addform.errors.as_data()) context = {"form": Addform, "formset": formset} return render(request, "add_property.html", context) Addform = AddPropertyForm( initial={"display_options": "buy"}, ) formset = ImageFormSet(queryset=AssetImages.objects.none()) context = {"form": Addform, "formset": formset} return render(request, "add_property.html", context) About editing an asset, I'm able to edit all the fields but the images, the best thing I managed to do was to add new images from there, but not editing the existed ones, I'm not sure how to make the form understands that I'm editing an image not creating a new one, also I wasn't able to display the images … -
Django RQ asyncio.TimeoutError
I am using django-rq and redis for queue tasks. Timeout:6000 but I get a timeout error. Somehow it works when I started worker first time and this code also works without queue Here my queue code: queue = django_rq.get_queue('default', is_async=True, default_timeout=6000) queue.enqueue(send_msg, args=(mesaj, cat, url, image_url, startDate, endDate),timeout=5400) Here my error code Traceback (most recent call last): File "/home/dir/venv/lib/python3.8/site-packages/rq/worker.py", line 1013, in perform_job rv = job.perform() File "/home/dir/venv/lib/python3.8/site-packages/rq/job.py", line 709, in perform self._result = self._execute() File "/home/dir/venv/lib/python3.8/site-packages/rq/job.py", line 732, in _execute result = self.func(*self.args, **self.kwargs) File "/home/dir/game/management/commands/game_bot/dc/dc_msg.py", line 370, in send_msg client.run(token) File "/home/dir/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run return future.result() File "/home/dir/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner await self.start(*args, **kwargs) File "/home/dir/venv/lib/python3.8/site-packages/discord/client.py", line 665, in start await self.login(*args, bot=bot) File "/home/dir/venv/lib/python3.8/site-packages/discord/client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) File "/home/dir/venv/lib/python3.8/site-packages/discord/http.py", line 300, in static_login data = await self.request(Route('GET', '/users/@me')) File "/home/dir/venv/lib/python3.8/site-packages/discord/http.py", line 192, in request async with self.__session.request(method, url, **kwargs) as r: File "/home/dir/venv/lib/python3.8/site-packages/aiohttp/client.py", line 1117, in __aenter__ self._resp = await self._coro File "/home/dir/venv/lib/python3.8/site-packages/aiohttp/client.py", line 619, in _request break File "/home/dir/venv/lib/python3.8/site-packages/aiohttp/helpers.py", line 656, in __exit__ raise asyncio.TimeoutError from None asyncio.exceptions.TimeoutError -
Merge or Union a list of dynamically created querysets - Django
I have a list of querysets as follows. Is there a way to merge all these query sets of a list into one query set ? The queryset elements of this list are dynamically determined. As in the example below it is three querysets in the list. In next hypothetical iteration it could be 40 querysets. capture_list =[<QuerySet [<Fields_Model: Fields_Model object (11)>]>,<QuerySet [<Fields_Model: Fields_Model object (12)>]>,<QuerySet [<Fields_Model: Fields_Model object (13)>]>] -
Como mostrar los registros asociados a una llave foránea con django [closed]
Tengo un proyecto en el cual relaciono zona con departamentos por medio de una llave foránea y departamento esta relacionado con municipio de la misma manera, ¿como podría hacer para que en una tabla me muestre las zonas y que departamentos tiene pero con todos sus atributos y no solo el numero de la llave al cual pertenece? -
Does pandas' `to_html` slow the page in Django down?
I am using JSON and request libraries to fetch the JSON of ExchangeRates API, and Pandas to read SCV and convert the table and render HTML in a front-end page, and Forex to convert the rates. I noticed that the page loads only after 45 seconds, I believe that the problem is in the CSV files and in the conversion with to_html(). I have 6 tables of Brazil, 5 tables of New Zealand and 7 tables of Uruguay, totalising 18 tables. Is there how to speed up the CSV and tables? from django.shortcuts import get_object_or_404, render from django.views import View from forex_python.converter import CurrencyRates from pathlib import Path import json import requests from pandas.io.parsers import read_csv class financial_planning(Mixin, View): def get(self, request, id = None, *args, **kwargs): template = "pages/financial-planning.html" context = { 'title': "Planejamentos financeiros", 'brazil_bills': self.brazil_bills(), 'nz_bills': self.nz_bills(), 'uy_bills': self.uy_bills(), } return render(request, template, context) def uruguayan_currency_conversion(self): url = 'https://v6.exchangerate-api.com/v6/YYYYEEESSS/latest/UYU' response = requests.get(url) data = response.json() return data def brazil_bills(self): cc = CurrencyRates() cad = cc.convert('BRL', 'CAD', 1) nzd = cc.convert('BRL', 'NZD', 1) usd = cc.convert('BRL', 'USD', 1) base_path = Path(__file__).parent file_path = (base_path / "static/data/brazil/bills.csv").resolve() c = pd.read_csv(file_path) c.loc["Total"] = c.sum() c["Item"].values[-1] = "Total" c["USD"] = (c['Price … -
import file where its column names different from the names in model caused rows with empty string
I would like to use django-import-export package to import some TSV files, but I'm facing some problems. In the file, I have the column names in uppercase like this: INDUSTRYGROUPTYPE, TOTALOFFERINGAMOUNT, TOTALREMAINING In the model I have the same name but with lowercase and undersocre like so: class Offering(models.Model): industry_group_type = models.CharField(max_length=260) total_offering_amount = models.CharField(max_length=17) total_remaining = models.CharField(max_length=17) The resource class look like this: class OfferingResource(ModelResource): industry_group_type = Field(attribute='INDUSTRYGROUPTYPE') total_offering_amount = Field(attribute='TOTALOFFERINGAMOUNT') total_remaining = Field(attribute='TOTALREMAINING') class Meta: model = Offering fields = ('id', 'industry_group_type', 'total_offering_amount', 'total_remaining') When the file is imported, empty rows are created that contain just empty string '', and there is no data. I need help to fix this, please. -
How to use default-character-set in django - mysql database connection
So, I was re-configuring my SQL and decided to move back from my.conf to settings.py (context: https://docs.djangoproject.com/en/3.2/ref/databases/#mysql-notes) 'read_default_file': '/path/to/my.cnf', # my.cnf [client] database = NAME user = USER password = PASSWORD default-character-set = utf8 So I was shifting from my.conf to settings.py I got an error TypeError: 'default-character-set' is an invalid keyword argument for connect My code: 'Options':{ 'default-character-set': utf8 } -
Set multiple route of new custom apps in Django
I have the following problem, I'm trying to add a new app (vuelos), so I have made the respective configurations in setting.py and urls.py, but when I try to open "vuelos/" route, appears the following message . Page not found 404 Using the URLconf defined in Portfolio.urls, Django tried these URL patterns, in this order: 1. admin/ 2. formulario/ The current path, vuelos, didn’t match any of these. I'm not able to get access to the route of the respective app. Here I leave here the code. Thank you in advance ! Portfolio.urls urlpatterns = [ path('admin/', admin.site.urls), path('formulario/', include("formulario.urls"), path('vuelos/', include("vuelos.urls"))) ] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py from vuelos.models import Vuelos from django.http import request from django.shortcuts import render # Create your views here. def index(): return render (request, "vuelos/index.html", { "Vuelos":Vuelos.object.all }) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index") ] -
How to create a group with some permissions
I'm working on a small project using Django / Rest Framework and i would like to add permissions and groups. i can't find any good tutorial about that, i did some research Google and here i found an answer about that : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) But here i can't see any logic about giving a user the permission to add or to edit or delete or to view. should i need just this piece of code to make permissions like ( edit for example ) or i should add some other codes ? Thank you -
How to access parent class fields from child class in Django Python
I have following inheritance between Image and ProfileImage & ThumbnailStaticImage classes in Django : class Image(models.Model): uuid = models.CharField(max_length=12, default="") extension = models.CharField(max_length=6, default=None) filename = models.CharField(max_length=20, default=None) path = models.CharField(max_length=64, default=None) class Meta: abstract = True def save(self, *args, **kwargs): if self.uuid is None: self.uuid = "T" + get_random_string(11).lower() def delete(self, *args, **kwargs): delete_message_send(self.path) super(Image, self).delete(*args, **kwargs) class ProfileImage(Image): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def save(self, *args, **kwargs): if self.extension is None: self.extension = ".png" if self.filename is None: self.filename = self.uuid + self.extension if self.path is None: self.path = self.user.path + "/" + self.filename class ThumbnailStaticImage(Image): video = models.ForeignKey(Video, on_delete=models.CASCADE, default=None) def save(self, *args, **kwargs): if self.extension is None: self.extension = ".png" if self.filename is None: self.filename = self.uuid + self.extension if self.path is None: self.path = settings.STORAGE.THUMBNAILDIRECTORY + "/" + self.filename super(ThumbnailStaticImage, self).save(*args, **kwargs) When I try to access the extension variable that should be inherited from Image class to ProfileImage class, it does not get that information from parent class. What is the purpose of inheritance if the child class does not get the fields that parent class has directly? How can I access the parent class fields from child class' overriding save method ? -
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??