Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Is there a way to manage admin panel edit permissions by model property in Django?
So, I want to be able to control write permissions for a model in Django admin panel using model property value. Here's an example: we have a model called Organization with property is_production, which is boolean. Also, we have two roles: Developers and Customer Support. I want users from Developers group to be able to edit Organizations with is_production = False, and users from Customer Support to be able to edit ones with is_production = True. Is there a no-code / low-code way to do it, like an extension / Django battery? Thanks for your time! -
Django: CloudFront wasn't able to connect to the origin
I'm working on a Django project and it's dockerized, I've deployed my application at the Amazon EC2 instance, so currently, the EC2 protocol is HTTP and I want to make it HTTPS so I've created a cloud front distribution to redirect at my EC2 instance but unfortunately I'm getting the following error. error: CloudFront attempted to establish a connection with the origin, but either the attempt failed or the origin closed the connection. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation. Generated by cloudfront (CloudFront) Request ID: Pa0WApol6lU6Ja5uBuqKVPVTJFBpkcnJQgtXMYzQP6SPBhV4CtMOVw== docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql - postgres-data:/var/lib/postgresql/data/ env_file: - prod.env app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web depends_on: - db env_file: - prod.env proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV … -
Redirect for a single file with Django and Nginx
I have a Django project serving static correctly files at /static. I'd like to serve a single .txt file in the root though, without the static in the URL. This is my Nginx section: location /ms11973759.txt { try_files /home/myhome/nms/static/ms11973759.txt; } I get a 404, although I can access the file via mysite/static/ms11973759.txt. What am I missing? -
retrieve only on column in filter in dry
how I get get only one column of my model using filter ids = model1.objects.filter(key=value) return model2.objects.filter(column__in=ids) in above example first filter should return list of ids of model1 and in second example data will be return using in of 1st result ids NOTE: model1 it's having number of field and one is id -
Is it possible to create a superuser with different inputs than a simple user in Django Rest Framework?
I am beginning a new project with Django Rest Framework, and I have a specifical need on the creation of a user: to create an account, you need to give information such as your birthdate, the birthdate of a friend, and several other info. But it would NOT be relevant for a superuser to give such information, that's why I am looking for a way to require different info for user and for superuser. Do you know if it's possible ? In the file models.py, I created 2 different classes : class UserProfile(AbstractBaseUser, PermissionsMixin) class SuperUserProfile(AbstractBaseUser, PermissionsMixin) These two classes require different info to create an account. In addition, I created a class to manage user profiles : class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, name1, firstName1, email1, name2, firstName2, birthDate2, password=None): """Create a new user profile""" email1 = self.normalize_email(emailParrain) user = self.model(emailParrain=emailParrain, name1=name1, firstName1=firstName1, name2=name2, firstNameUser=firstNameUser, birthDateUser=birthDateUser) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given details""" user = self.create_user(email,password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user But when I do this, I cannot create a superuser with only the info sub-mentionned (email, name, password). -
django admin panel sort order display
hey guys i want to change the sort of my models in the admin panel with django for example i want to have the "categories" on the top of the list how can i do that? is it possible?! ` class SongAdmin(admin.ModelAdmin): list_display = ['name', 'artist', 'album', 'slug'] list_filter = ['created_date'] search_fields = ['name', 'artist__name', 'album__name'] class Meta: model = song admin.site.register(song, SongAdmin) admin.site.register(categories) admin.site.register(album) admin.site.register(artist) admin.site.register(PlayList) admin.site.register(PlayListSongs) admin.site.register(discount_codes) ` -
Some guidance on json structure to a django DRF serializer
I have a model structure like this: model: server_name: str description: str owner: str but the application sending data to my app use a json format I am not sure on how to create a serializer for. For multiple entries it looks like this { "server1": { "description": "desc of server 1", "owner": "service name" }, "server2": { "description": "desc of server 2", "owner": "service name" } } but I am not sure on how to get it into something matching my model. This is the structure I would like it to have in the serializer [ { "server_name": "server1", "description": "desc of server 1", "owner": "service name" }, { "server_name": "server2", "description": "desc of server 2", "owner": "service name" } ] Any suggestions on this one?