Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not accounting for Daylight Savings Time
The issue is pretty simple, but I can't for the life of me find any information on it. Based on my internet searches, it seems like this should be a non-issue; Django should be doing this automatically. My issue is that ever since DST began, Django has been converting times to displays on the webpages 1 hour before the times should be. I say converting to because I've enabled "USE_TZ" in settings, so the times are being saved to the database in UTC, but the times are incorrectly converted to EST as they are one hour behind. What could be causing this? -
How to get one value (clicked one) from for loop in JS addEventListener Django project
Im trying connect JS inside my Django project I got message in console that HTMLCollection(2) [p.currency-one, p.currency-one] HTMLCollection(2) [input.amount-one, input.amount-one] app.js:21 Uncaught TypeError: c1.addEventListener is not a function at app.js:21:4 (anonymous) @ app.js:21 JS file const c1 = document.getElementsByClassName("currency-one"); const c2 = document.getElementById("currency-two"); const amount1 = document.getElementsByClassName("amount-one"); const amount2 = document.getElementById("amount-two"); const swap = document.getElementById("swap"); const theRate = document.getElementById("rate"); console.log(c1,amount1) function calculate() { const curr1 = c1.innerHTML; const curr2 = c2.innerHTML; const rate = parseInt(amount1.value) / parseFloat(amount2.innerHTML); theRate.innerText = `You can buy maximum -> you wallet money ${amount1.value} ${curr1} = ${rate} ${curr2}`; } // THIS PART OF THE CODE does not know how to get two pieces of information from one //class, how to get through it ? c1.addEventListener("change", calculate); amount1.addEventListener("input", calculate); c2.addEventListener("change", calculate); amount2.addEventListener("input", calculate); swap.addEventListener("click", () => { const flash = c1.value; c1.value = c2.value; c2.value = flash; calculate(); }); view.py def a(request,crypto_name, fiat_currency=None): buttons = [ {"currency_type": "USD", "active": "", "display_text": "USD"}, {"currency_type": "EUR", "active": "", "display_text": "Euro"}, {"currency_type": "CNY", "active": "", "display_text": "Chinese Yuan"}, {"currency_type": "JPY", "active": "", "display_text": "Japanese Yen"}, ] for button in buttons: if button['currency_type'] == fiat_currency: button['active'] = 'active' crypto_detail_view = load_detail_crypto(crypto_name,fiat_currency) user_purchased_currencies = UserPurchasedCurrencies.objects.filter(user = request.user) user_walet_info_amount_and_name = [x for i … -
Django MEDIA not accessible
My Django app is unable to see MEDIA directory. When I run one of my views I need to open a file. The scenario is to: take a record with requested id from data base get the file path to a file send the file to external server for OCR purposes models.py from django.db import models from django.contrib.auth.models import User class Homework( models.Model): title = models.CharField(max_length = 200, default = None) image = models.FileField(upload_to='user_scans/') author = models.ForeignKey(User, default=None, on_delete = models.CASCADE) latex = models.TextField(default = "No LaTeX Here") settings.py: from pathlib import Path from django.conf.urls.static import static BASE_DIR = Path(__file__).resolve().parent.parent ... DEBUG = True ... STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = "/media/" views.py import requests import json from django.shortcuts import render, get_object_or_404 from .models import Homework def create_homework(request): if request.method == 'GET': #some GET stuff if request.method == 'POST': homework = Homework() homework.title = title homework.image = image homework.author = author homework.save() id = homework.id json_to_mathsnip(id) .... def json_to_mathsnip(id): homework = get_object_or_404(Homework, pk=id) f = open(homework.image.url, "rb") ... some later stuff ... Unfortunately I'm constantly running into an error: FileNotFoundError at /homework/new [Errno 2] No such file or directory: '/media/user_scans/kwa.png' My … -
wsgi_mod fails to host Django with python3.10 on CentOs
My goal is to host Django app on CentOs 7 with python3.10 I've manage to download and configure Python, sqlite to work with manage.py runserver but it dosn't work when i try to host it with apache. Apache throws error: ImportError: /usr/local/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so: undefined symbol: sqlite3_trace_v2 Installed Versions System: CentOs 7 Python: 3.10.4 sqlite: 3.28.0 mod_wsgi: 4.9.0 Apache: 2.4.6 Apache .conf WSGIScriptAlias / /var/www/portal/portal/wsgi.py WSGIPythonPath /var/www/portal/:/var/www/venv/lib/python3.10/site-packages <VirtualHost *:80> ServerName 192.168.1.25 Alias /static /var/www/portal/static/ DocumentRoot /var/www/portal <Directory /opt/portal/static> AllowOverride All Require all granted Allow from all </Directory> <Directory /var/www/portal/portal> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Full Traceback: Traceback (most recent call last): File "/var/www/portal/portal/wsgi.py", line 22, in <module> application = get_wsgi_application() File "/var/www/venv/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/venv/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/var/www/venv/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/var/www/venv/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from … -
Gallery Field in django
I want to implement extra images for my products in a Django webstore. I want to know if there is any fields,(or alternatively ways) to have an unknown number of images stored under a certain name in Django models -
How do i write the django query filter when multiple joins are involved in Django?
I would like to translate the below SQL query for the schema shown in the snapshot into Django. How do I accomplish this? select * from purchase inner join customer on customer.id = purchase.customer_id inner join seller on seller.id = purchase.seller_id inner join manager on seller.id = manager.seller_id -
Bypassing Cloud Run 32mb error via HTTP2 end to end solution
I have an api query that runs during a post request on one of my views to populate my dashboard page. I know the response size is ~35mb (greater than the 32mb limits set by cloud run). I was wondering how I could by pass this. My configuration is set via a hypercorn server and serving my django web app as an asgi app. I have 2 minimum instances, 1gb ram, 2 cpus per instance. I have run this docker container locally and can't bypass the amount of data required and also do not want to store the data due to costs. This seems to be the cheapest route. Any pointers or ideas would be helpful. I understand that I can bypass this via http2 end to end solution but I am unable to do so currently. I haven't created any additional hypecorn configurations. Any help appreciated! -
django how to add a model as a column of another model
So, I have a Items model in which is the data about all my items. I have another watchlist model in which a username and an itemname are stored. I get all the items the user has stored in their watchlist with Watchlist.objects.filter(username=request.user.username) but how do I get all the info related to those usernames and send it to template? -
when deploy django app to heroku it show this type of error what to do?
error: [Errno 2] No such file or directory: 'build/scripts-3.9/runner' ---------------------------------------- ERROR: Failed building wheel for MyProject Running setup.py clean for MyProject Building wheel for psycopg2 (setup.py): started Building wheel for psycopg2 (setup.py): finished with status 'done' Created wheel for psycopg2: filename=psycopg2-2.9.3-cp39-cp39-linux_x86_64.whl size=579697 sha256=aff6ba164506cddbb1b1b007118ccf1363be963eb13deff8c671df4c4604c5d0 Stored in directory: /tmp/pip-ephem-wheel-cache-urp59i8g/wheels/b3/a1/6e/5a0e26314b15eb96a36263b80529ce0d64382540ac7b9544a9 Successfully built comtypes iface psycopg2 Failed to build MyProject Installing collected packages: sqlparse, pyparsing, asgiref, whitenoise, tomli, py, psycopg2, pluggy, packaging, MarkupSafe, iniconfig, Django, dj-database-url, attrs, tzdata, pywifi, pytest, MyProject, Jinja2, iface, gunicorn, django-heroku, comtypes, colorama, atomicwrites Running setup.py install for MyProject: started Running setup.py install for MyProject: finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_t5d7cl9/myproject_6028566010f545bea380a8fe2531b2ca/setup.py'"'"'; __file__='"'"'/tmp/pip-install-_t5d7cl9/myproject_6028566010f545bea380a8fe2531b2ca/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-vwqkuw1t/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/MyProject cwd: /tmp/pip-install-_t5d7cl9/myproject_6028566010f545bea380a8fe2531b2ca/ Complete output (17 lines): running install running build running build_py creating build creating build/lib creating build/lib/pkgA copying pkgA/modA_2.py -> build/lib/pkgA copying pkgA/modA_1.py -> build/lib/pkgA copying pkgA/__init__.py -> build/lib/pkgA creating build/lib/pkgB copying pkgB/__init__.py -> build/lib/pkgB copying pkgB/modeB.py -> build/lib/pkgB running build_scripts creating build/scripts-3.9 warning: build_scripts: runner is an empty file (skipping) error: [Errno 2] … -
Javascript/Django : How display a PDF in a new browser from a button
I am a newbee in Django and Javascript. I did an app where an user can upload files to an azure blob storage. When they are uploaded, they are added to a list of files uploaded. The user then can download or display them. I have done the part to download and now I need to do the second part. I have put an icon in the template, but I do not know what I should do after and I have few questions Should I create a new view/url to display them by taking the pk value of the database. Is it possible to diplay it in same bowser next to the list of files. Would it be easier to display it in a new browser ? Anyone can explain me how I should go on with this icon ? How can I write a script in JS to display the pdf. Thank you html {% extends 'home.html' %} {% load static %} {% block content %} <link rel="stylesheet" href="{% static 'test15.css' %}"> <div class="upload-app"> <div class="upload-in"> <h2>Upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% if url %} <p>Uploaded files : <a href="{{url}}">{{url}}</a></p> {% … -
How to join tables by list of ids in Django ORM
I have two tables - Players and Buildings. For example: class Players(models.Model): username = models.CharField(max_length=500) buildings = models.CharField(validators=[int_list_validator], default=list, max_length=100) class Buildings(models.Model): building_name = models.CharField(max_length=500) Player can have a lot of buildings, there are in the Player.buildings field as list of ids. I need to write a query to get building information for the player. In Postgres SQL, I got that query: SELECT * FROM players p LEFT JOIN buildings b on b.id=ANY(buildings) where p.id = %s; But how I can write that SQL query, using Python and Django ORM? -
How do i omit existing record django modelformset?
I am attempting to duplicate a form and have it show just two fields using a modelformset. When I go to run the code django returns all the records in my data base and the requested two empty fields. How do I omit the existing records and only return an empty form every time. #views def create_player_view(request): """" allows users to name to players competing vs one another """ PlayersFormSet = modelformset_factory(Players, fields=["playerName",], extra=2, form=PlayerForm) if request.method == "POST": form = PlayersFormSet(request.POST) if form.is_valid(): message = "" form.save() else: message = "Form could not be completed" return render(request, "create_player.html", {"message":message}) else: return render(request, "create_player.html", {'form': PlayersFormSet()}) #model class Players(models.Model): playerName = models.CharField(max_length=10) -
Duplicate column name when running tests in Django
I have a problem with my code. My friend helped me to write some code in JavaScript, but to do that part of code, he had to add a field with the "db_column" option. After he has done that, when i run the tests, i have an error: "duplicate column name: ID". Now my friend can't help me anymore, and i can't find a solution for this... Here is the models.py: class Item(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50, validators=[RegexValidator('helmet|torso|pants|gauntlets|weapon|accessory')]) bonus = models.ForeignKey(Statistics, on_delete=models.CASCADE) durability = models.IntegerField() image = models.ImageField(upload_to='DeepDungeon/static/images/items') itemId = models.IntegerField(db_column='ID') And here is the error: Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/manuel/Programmazione/PyCharm/DeepDungeon/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/Users/manuel/Programmazione/PyCharm/DeepDungeon/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: duplicate column name: ID -
Google Scatterchart doesn't show any data
I was trying to create a ScatterChart in a div on a django project using JS but instead there is only a red square in the div. When I try to select the space where it should be, I can copy the data but it doesn't show itself visually, even when I try to change its font color or width and height of div. google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(() => { google_carregado = true; atualizar_grafico(); }); function atualizar_grafico() { if(!google_carregado) return; const dados = registros.map( e => [ e.ganho_anual, e.angle_anual ]); var data = google.visualization.arrayToDataTable([ ['Angle', 'Custo'], ...dados ]); var options = { title: 'Angle vs. Custo', hAxis: {title: 'Angle', minValue: 0, maxValue: 50}, vAxis: {title: 'Custo', minValue: 0, maxValue: 50}, legend: 'none' }; var chart = new google.visualization.ScatterChart(document.getElementById('chart_div')); chart.draw(data, options); } -
Unable to Create/Edit/Delete objects on Django Admin - Foreign Key Constraint Failed
Encountering some weird behavior developing a django app. I'm using sqlite3 locally and on production at the moment. Locally the admin interface allows me to create/edit/delete objects as expected. In production, cloned from the exact same repo of code I am getting IntegrityError, Foreign Key constraint failed errors when attempting to create, edit, or delete objects. I have a CustomUser model that I use as AUTH_USER_MODEL. Users can sign up for the service without problem locally and on production, thereby creating a CustomUser object for themselves. The strange thing is on production I cannot go about creating a user using the django admin interface without encountering the aforementioned error. I thought maybe the issue was related to my use of a CustomUser model as AUTH USER MODEL, however even attempting to create/edit/delete other objects I encounter the same error. I'm not sure how to go about debugging this. Any help would be greatly appreciated! -
How to ensure daily email is only sent once over multiple instances in Django app?
I am trying to scheduling a job/CRON job, on Django app that uses APScheduler to send out a daily email at a scheduled time morning 9 AM. And We have 5 instances/pods in production. The problem is each day I am getting 5 email and I suspecting its due to number of instance/pod. Cron is running on all instance/pod. How to prevent the daily email from being sent out by all instances. from apscheduler.schedulers.background import BackgroundScheduler def cron_job(): scheduler = BackgroundScheduler() scheduler.add_job(send_daily_emails, "cron", day_of_week='fri', hour=8, minute=0, id="send_daily_emails_trigger", replace_existing=True) scheduler.start() Python version - 3.5+ Django Version - 2.2.3 APScheduler - 3.9.1 So this is run when my app initializes--this creates a background scheduler that runs the send_daily_emails function at 9AM each morning. The send_daily_emails function is exactly that--all it does is send email to couple of folks. My problem is that there are five instances of the app running, five separate background schedulers will be created and thus the emails will be sent five times each day instead of once. How to send only one email or stop other emails to go. Thanks in Advance :) -
How do you pass a variable from javascript to python (oTree) or django?
I have some created some variables in Javascript to tracker how long an individual holds a button. I would like to pass these variables within a class in python (oTree) to store the data. So, suppose the Javascript code is as follows: let javascriptvariable = 0; This javascriptvariable will be updated as the user clicks the button, so let's say the final value is javascriptvariable = 100. The python code is below. class DisplayCharacteristics2(Page): form_model = 'player' pythonvariable = javascriptvariable @staticmethod def vars_for_template(player: Player): return { "var1": player.var1, } I tried created an empty variable, but I get an error which says something like javascript can't "add" to a null variable. I also tried using django in combination with javascript (see below), but javascript cannot add to a null variable. I tried to let it equal to zero first, but then I only get data points of 0. let javascriptvariable = `{{ pythonvariable|safe }}` Any leads will be appreciated! Thanks in advance. -
Making queries Django
I'm pretty new to queries and Django so need a help with this case. There are five models: class User(models.Model): host = models.ForeignKey('Host', related_name='users') hobbie = models.ForeignKey('Hobbie', related_name='users') skill = models.ForeignKey('Skill', related_name='users') profile_id = models.UUIDField(blank=True, null=True) country = models.CharField(max_length=20) status = models.CharField(max_length=10) category = models.ManyToManyField('Category', related_name='users', blank=True) class Host(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Hobbie(models.Model): hobbie_code = models.CharField(max_length=3) active = models.CharField(max_length=4) class Skill(models.Model): object_type = models.ForeignKey(related_name='users') object_id = models.PositiveIntegerField() skill_name = models.CharField(max_length=128) class Category(models.Model): permissions = models.CharField(max_length=35) category_name = models.CharField(max_length=256) Need to get fields: host_id, hobbie_code(from model Hobbie), skill_name(from table Skill), profile_id, country, status, category_name (from table Category) Right now using this queries to get all values, but feel that it is not correct. yesterday = datetime.date.today() - datetime.timedelta(days=1) users_data = User.objects.all() user_data = Users.objects.filter(created_on__date=yesterday).values( 'host_id', 'country', 'status', 'profile_id').exclude(profile_id='0000000') hobbie_data = Hobbie.objects.filter(users__in=user_data).values_list( 'hobbie_code', ) skill_data = Skill.objects.filter(users__in=user_data).values_list('skill_name',) category_data = Category.objects.filter(users__in=user_data).values_list('category_name',) -
Should I import a model only to use type hint in Python?
I have noticed that in many cases I am trying to use type hints in a file that doesn't have this class imported. I wonder whether using type hints is reasonable in such scenario (which means that I will have to import the class)? -
convert HTTP protocol to HTTPS AWS EC2 instance
I'm new to AWS and I have a dockerized Django application deployed to AWS EC2 so currently, the protocol of my EC2 instance is HTTP but I want to make it HTTPS. -
Communication between a Django Web App and an external Server running python scripts
I am currently working on a web page using Django. This website aims at displaying results of different simulations. I can not use the code of some simulation directly in my Django backend. But the code owners allow me to do a black box simulation using their own servers. So the idea is to first send some sort of request with data to the server. The data was inputed earlier by the user and saved in the django database. Then the server receives the data and excecutes a simulation (a python script) using this data. After the simulation is finished the data is sent back to my django backend, so my django backend receives some kind of response. I researched a lot on this topic but could not really find something I could use. I saw stuff like python sockets, socket.io, websockets, django rest framework and django channels, but I did not really see how I could apply one of these libraries to my case. How do I achieve what a described earlier? How can I connect my django project to a remote server (in a different city)? Where do I start? I tried to implement a server and client … -
is there any way to override this Entry.objects.filter().update() function?
Entry.objects.filter(is_published=True).update(views=set_view) is there any way to override this update() in filter().update() function. Thanks in advance. -
How to determine if a template block is empty/blank in Django?
I am using Django templates for my website, and I have a template block for the webpage's title: I have a base template (base.html), which formulates the <title> element like this: <title>{% block title %}{%endblock %} - Website Title</title> And then, in each page template, I put a block like so: {% block title %}Webpage Name Here, e.g. About Us{% endblock %} which would then give me: <title>Webpage Name Here, e.g. About Us - Website Title</title> Is there a way to determine programmatically, within the base template, the size/length/content of the title block? I want to make it so that on my homepage, there is no "-" in the title, it just says "Website Title". I figure the best way would be to do something similar to this: <title>{% block title %}{% end block %}{% if title|length > 0} - {/if}Website Title</title> ... but I can't figure out for the life of me how to determine the length of the {% block title %} which is being passed from the page template. -
Update email bcc recipient in email backend
I am building a mail backend that should add a specific address to the bcc of an email. from django.conf import settings from djcelery_email.backends import CeleryEmailBackend class BCCEmailBackend(CeleryEmailBackend): def send_messages(self, email_messages): for i, message in enumerate(email_messages): if settings.DEFAULT_BCC_EMAIL is not None: message.bcc.append(settings.DEFAULT_BCC_EMAIL) super().send_messages(email_messages) When I run my test, the bcc is not set. @override_settings(DEFAULT_BCC_EMAIL="should_be_send@bcc.de") def test_default_bcc_email(self): self.assertEqual(settings.DEFAULT_BCC_EMAIL, "should_be_send@bcc.de") msg = EmailMultiAlternatives( self.subject, self.text_content, "test@sender.de", ["test@recipient.de"] ) msg.attach_alternative(self.html_content, "text/html") msg.send() #... # This test always fails self.assertListEqual(m.bcc, ["should_be_send@bcc.de"], "Default bcc should be set") When I set the bcc directly when initialising EmailMultiAlternatives my test is succeeding. -
searchable dropdown list for adding a new post in django
hey guys in my new project I have too many data and finding a parent foreign key from a drop down list is impossible . so i need to have a search field inside my dropdown list but don't know how can i do that. #i uploaded an image below click to see image class song(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) artist = models.ForeignKey(artist, on_delete=models.DO_NOTHING) album = models.ForeignKey(album, on_delete=models.DO_NOTHING) slug = AutoSlugField(populate_from=['artist', 'name']) # s_slug = models.SlugField(max_length=250, unique=True, verbose_name="Route To") status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') song_link = models.CharField(max_length=500) video_link = models.CharField(max_length=500) name = models.CharField(max_length=150) cover = models.CharField(max_length=300) explicit_content = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True)