Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django doesn't serve all js files in development
I have two js files in my static folder, main.js and animation.js. When I run py manage.py runserver and go to localhost, I only see main.js. I've tried hard refreshing Chrome and Firefox, running collectstatic, and it's still the same. One time when I first loaded the page I saw both js files, but after clicking around the site, the animation.js file just disappeared. My terminal output shows that both js files were found. I'm confused why only one shows up in the browser. If both were missing that would indicate something wrong in settings, but I don't know with just one missing. What could be my problem? Here's my settings.py: DEBUG = TRUE STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -
Problem sending a signal when adding a django child model
I'm facing the problem that I can't track the creation of an object in a child model. I am using inline in my model. And I want all objects of child model AuthUrl to be output when saving ServerAuth model. This code works correctly and outputs any changes but when I add a new AuthUrl object I get the error that supposedly the id doesn't exist. How can this be fixed? class ServerAuth(models.Model): name = models.CharField(max_length=120, default="name") allow_default = models.BooleanField() class AuthUrl(models.Model): url = models.CharField(max_length=120) server_auth = models.ForeignKey(ServerAuth, on_delete=models.CASCADE, related_name="auth_urls") @receiver(post_save, sender=ServerAuth) @receiver(post_save, sender=AuthUrl) def do_something(sender, **kwargs): auths = AuthUrl.objects.filter(server_auth_id =kwargs.get('instance').id) print(auths) -
Handling server timeout (503) for request with heavy calculations
I deployed my first project in which I'm visualising clusters in a user's Spotify playlist, using Django for backend and React for frontend. One of the services of my Django backend receives an array of features of the tracks in the selected playlist. These features are then reduced using Scikit Learn's TSNE. However, it may take more than 30 seconds before the service returns a response with output to visualise, meaning that the server times out with code 503. I'm looking for suggestions to solve this issue and any would be appreciated. -
sign up form doesn't work (CSRF token missing or incorrect.) django
I'm trying to do a registration form where users get added to users group in the admin interface but for some reason, the registration form doesn't get saved in the database instead it gives me this error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. can someone tell me what I'm missing here? decorators.py from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'user': return redirect('home') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function views.py @unauthenticated_user def sign_up(request): data = CreateUserForm() if request.method == 'POST': data = CreateUserForm(request.POST or None) if data.is_valid(): user = data.save() username = data.cleaned_data.get('username') group = Group.objects.get(name='user') user.groups.add(group) messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'info':data,} return render(request, 'signup.html', context) … -
Django - Change the default invalid email error message in ModelForm
I'm using a ModelForm to save users. The User model is the default django.contrib.auth.models.User. My ModelForm class is like this class RegisterForm(ModelForm): password = CharField(label="Password", widget=forms.PasswordInput(attrs={'class': 'form-control'})) confirm_password = CharField(label="Confirm your password", widget=forms.PasswordInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'email', 'password') labels = { 'username': 'User name', 'email': 'E-mail', } widgets = { 'username': TextInput(attrs={'class': 'form-control'}), 'email': TextInput(attrs={'class': 'form-control'}) } When I put an invalid email, I have in RegisterForm.email.errors the message "Enter a valid email address." How do I change this message? -
The ModelResource Meta field import_id_fields seems that it doesn't work as expected
I'm building a web app using the Django framework and the django-import-export package. I would like to import data from files and want to prevent importing it twice to the DB. For this, I used the import_id_fields when declaring the resource class, but it seems that it doesn't work as expected. 1- The first time I import the file everything is working fine and rows created in the DB. 2- The second time I import the same file, also new rows created in the DB (here is the problem, this is not supposed to happen) 3- The third time I import the same file, here I get errors and no rows added to the DB. So I would like to know if this is normal behavior or not, and if is normal I would like to know how can I stop the import in point 2 and show the errors. You can find below portions from the code and the error messages. # resources.py class OfferingResource(ModelResource): ACCESSIONNUMBER = Field(attribute='company', widget=ForeignKeyWidget(Company, 'accession_number')) quarter = Field(attribute='quarter') # other fields ... class Meta: model = Offering import_id_fields = ('ACCESSIONNUMBER', 'quarter') def before_import_row(self, row, row_number=None, **kwargs): Company.objects.get_or_create(accession_number=row.get('ACCESSIONNUMBER')) # models.py class Company(models.Model): accession_number = models.CharField(max_length=25, … -
Form for editing a page doesn't work in Django (CS50 Project)
I am creating a Wikipedia like web app in django and one of the features is that the user is able to edit a page. I have tried to code this, however it doesn't seem to work. I have spent hours trying to figure out the problem and I am unable to fix it. When I enter data into the form, it isn't getting saved onto the file. I press the edit page link, it takes me to editpage.html (which is /wiki/pageName/editpage) and I can type in different data, but when I press the save button, nothing is saved and when I look at the actual file on the disk, it is still the original and none of the edits have been saved. my views.py editpage function: def editpage(request, title): if request.method == 'post': form = editPageForm(request.POST) if form.is_valid(): pageTitle = form.cleaned_data['title'].capitalize() pageContent = form.cleaned_data['content'] util.save_entry(pageTitle, pageContent) return HttpResponseRedirect(f'/wiki/{pageTitle}') else: return render(request, 'encyclopedia/editpage.html', { 'title': title, 'content': util.get_entry(title) }) my urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path('<str:title>/editpage', views.editpage, name='editpage'), path('newpage', views.newpage, name='newpage'), path(f'<str:title>', views.display, name='display') ] the editpage.html website: {% extends "encyclopedia/layout.html" %} {% block title %} Editing: {{ title }} … -
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?