Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web deployment using AWS Lightsail
I'm new to deploying websites. I build a React frontend with a Django backend and a mysql database. I dockerized it and purchased a domain. Now I would like to bring it to production but the options seem endless. I want to use AWS Lightsail but I am not sure whether to choose the containers or instances and what the difference is, containers are twice as expensive but what do you get for that money? Also, is it possible to run a Mysql database in the Lightsail instance or container, or do I need to purchase a database seperately? If anyone could explain this to my I would highly appreciate it! -
Filter number-series from IntegerField() of a Django model
Is it possible to query an IntegerField() of a Django Model within a view for a series of numbers? Since I have some additional or filter conditions I would like to use with Q(), and casting a string with extra() does not seem to be a good option in combination. Something like this would be the desired behavior: if request.POST.get('number', None): search_query = Q() search_query |= Q(product__contains=request.POST['number']) A number like 123 should filter IDs like these: 123, 1123, 1001230 -
Django Filter ManyToMany
I have 3 models on a project that I need some help properly filtering data in the template. I have a home page that I would like "subjects" to be populated by newest created from boards the user is "subscribed" to. Here are my models: class Board(models.Model): title = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=500) subscribers = models.ManyToManyField(User, related_name='subscribed_boards') created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created', ) def __str__(self): """Unicode representation for a board model.""" return self.title class Subject(models.Model): title = models.CharField(max_length=150, db_index=True) body = models.TextField(max_length=5000, blank=True, null=True) author = models.ForeignKey(User, related_name='posted_subjects', on_delete=models.CASCADE) board = models.ForeignKey(Board, related_name='submitted_subjects', on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created', ) def __str__(self): """Unicode representation for a subject model.""" return self.title -
I have to send large json in packets asynchronously to multiple users with having sessions and remembering the packets send
Problem statement: We have a big static json file and more than one user wants to access this json data for some processing. But the problem we are facing is that this json file contains a lot of data and sending this whole data at once will make our system super slow. Tasks: Try to send data in a chain of patches(packets). This data will be accessed by more than one user, so you also need to store some information regarding which patch was accessed by which user. Create an environment where each user will receive the data asynchronously without any waiting timeout. When the user sends “START” to the socket, it should send the first patch and when the user sends “NEXT”, the websocket should send the next patch. Note: Remember this data is fetched by more than one user at the same time, so need to save the session accordingly. -
Django: accessing foreign key from within template
I'm trying to toggle the text on a button based on an if statement within the Django template. If the product is not already part of the user's watchlist, then I'd like the text on the button to read as "Add". Otherwise, I would like the text on the button to read as "Remove". Here is my code: views.py def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) if request.method == 'POST': user = User.objects.get(username=request.user) if request.POST.get('button') == 'Watchlist': if not user.watchlist.filter(listing=listing): watchlist = Watchlist() watchlist.user = user watchlist.listing = listing watchlist.save() else: user.watchlist.filter(listing=listing).delete() return HttpResponseRedirect(reverse('listing', args=(listing.id,))) models.py: class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=CASCADE, related_name='watchlist') listing = models.ForeignKey(Listing, on_delete=CASCADE, related_name='listing') class Listing(models.Model): title = models.CharField(max_length=50) description = models.TextField(verbose_name="Description") listing.html template: <div> <form action="{% url 'listing' listing.id %}" method="POST"> {% csrf_token %} {% if listing not in listing.watchlist %} <button type="submit" name="button" value="Watchlist" class="btn btn-primary">Add to Watchlist</button> {% else %} <button type="submit" name="button" value="Watchlist" class="btn btn-primary">Remove from Watchlist</button> {% endif %} </form> </div> listing is Foreign Key in the Watchlist class. I'm trying to do what I think is a simple test to determine whether the item is not already in the Watchlist. Here is my attempt: {% if listing not in listing.watchlist %} … -
How to create a model object with OneToOneField
I have a chat application and I'm trying to save a message. My message model has a OneToOneField, I'm doing this because I want to display a profile image with the message in templates. Here is my code..... Consumers.py - here is where the message should save @sync_to_async def save_message(self, username, room, message): Message.objects.create(author = username, room = room, content = message) Models.py - here is my Message and Profile model class Message(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE) room = models.CharField(max_length = 255) content = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: ordering = ('date_added', ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) And here is a part of my Template where I want to display the messages <main> <div id="chat-text"> <div id=message> {% for m in messages %} <img id="imageid" src="{{ m.author.profile.image.url }}"> <b id="b2" style="color: rgb(252, 93, 93);"> {{m.author}}</b> <br> </b> {{ m.content }} <br> {% endfor %} </div> </div> <div id="message-box"> <div class="input-container"> <input id="file-send" type="button"> <input id="input" placeholder="Type a message here..." type="text"> <input id="submit" type="submit" … -
TypeError: 'tuple' object is not callable, I checked the tuple but it seems alright
from django.db import models from django.contrib.auth.models import User from django.utils import timezone Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class Post(models.Model):`` #problem with options options = [ ('draft', 'Draft') ('published', 'Published') ] class PostObjects(models.Manager): def get_queryset(self): return super(self).get_queryset().filter(status='published') ##models.py->class Post-> category = models.ForeignKey(Category, on_delete=models.PROTECT,default=1)what is default=1???? category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=250) excerpt = models.TextField(null=True) content = models.TextField() slug = models.SlugField(max_length=250, unique_for_date='published') published = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE(),related_name='blog_posts') status = models.CharField( max_length=10, choices = options ,default='published') objects = models.Manager() # default postobjects = PostObjects() #customised manager class Meta: ordering = ('-published',) def __str__(self) -> str: return self.title -
Why does mypy raise error when I run it with pre-commit for django-reset-framework?
I'm trying to automate my tests and code static analysis with pre-commit.My .pre-commit-config.yaml is like below: # . # . # . - repo: https://github.com/pre-commit/mirrors-mypy rev: 'v0.910' hooks: - id: mypy args: [--no-strict-optional, --ignore-missing-imports] exclude: "[a-zA-Z]*/[a-zA-Z]*/(migrations)/(.)*" additional_dependencies: [ 'tokenize-rt, 'djangorestframework-stubs', 'django-stubs', ] When I run the pre-commit run --all-files I get the following error: Error constructing plugin instance of NewSemanalDjangoPlugin Traceback (most recent call last): File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/bin/mypy", line 8, in <module> sys.exit(console_entry()) File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/lib/python3.8/site-packages/mypy/__main__.py", line 11, in console_entry main(None, sys.stdout, sys.stderr) File "mypy/main.py", line 87, in main File "mypy/main.py", line 165, in run_build File "mypy/build.py", line 179, in build File "mypy/build.py", line 229, in _build File "mypy/build.py", line 475, in load_plugins File "mypy/build.py", line 453, in load_plugins_from_config File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/lib/python3.8/site-packages/mypy_django_plugin/main.py", line 104, in __init__ self.django_context = DjangoContext(django_settings_module) File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/lib/python3.8/site-packages/mypy_django_plugin/django/context.py", line 88, in __init__ apps, settings = initialize_django(self.django_settings_module) File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/lib/python3.8/site-packages/mypy_django_plugin/django/context.py", line 72, in initialize_django apps.populate(settings.INSTALLED_APPS) File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/alipqb/.cache/pre-commit/repo94ds7xs0/py_env-python3.8/lib/python3.8/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' But I have installed both … -
How to send user a message and create a channel right after installation of Slack app
As the title suggests, I'm wondering how we could: Create a channel Send user an initial message right after the user installs the Slack app (distributable app) for the first time in a workspace? A similar question was asked previously but the answer was too concise, and I wonder if someone could be so kind to give a hint using this sample Django Slack app code? Cheers. -
Django How to Filter Model Instances and also Related Objects for Each Instance. Nested Filtering?
I have three models, Genre, Movie and Review. Each genre can have multiple movies, and each movie can have multiple reviews. I have been trying to filter the related objects of a Genre instance such that the queryset contains only active movies, and each of those active movies contains only active reviews. models.py class Genre(models.Model): name = models.CharField(max_length=160) class Movie(models.Model): genre = models.ForeignKey(Genre, null=True, on_delete=models.CASCADE, related_name='movies') title = models.CharField(max_length=160) active = models.BooleanField(default=True) class Review(models.Model): movie = models.ForeignKey(Movie, null=True, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) Basically, I am looking for something roughly like genre1.movies.filter(active=True).reviews.filter(active=True), if something of this sort of possible. How can I obtain a queryset from a Genre instance which contains only active movies and reviews? Thank you for your time! -
Django Media assets in Forms, how to defer/async JS assets
The official docs explain how to automatically adds assets for certain widgets., from thier example: from django import forms class CalendarWidget(forms.TextInput): class Media: css = { 'all': ('pretty.css',) } js = ('animations.js', 'actions.js') What it does not describe is how to make JS assets deferred or async loaded, e.g. <script defer src="https://myserver.com/static/animations.js">/script> -
Docker, Django, Gunicorn, Nginx, and a 502 bad gateway error
I am relatively new to Docker and have ran into an problem that I cant seem to find a solution for. I have two Docker stacks that are running Nginx and Django however, one of the stack is reachable via web browser and the other times out with a bad gateway error. Both stacks are running on the same server but on different ports the stack that runs on port 8000 is reachable the stack that runs on 8010 throws the 502 error. I have verified that the ports are open on the host and that I am able to ping from the Nginx container to the Django container. I have also spun up each stack separately which ended with the same results. I am running out of ideas so, any insight would be appreciated. Server: VM - Red Hat Enterprise Linux Server release 7.9 (Maipo) Docker version 20.10.3, build 48d30b5 Working Docker-compose file version: '3.3' services: web: build: context: ./ dockerfile: Dockerfile command: sh -c "python manage.py makemigrations && python manage.py migrate && gunicorn laitteiden_saatavuus.wsgi:application -w 3 --bind 0.0.0.0:8000" volumes: - static_volume:/home/app/web/static expose: - 8000 - 1433 env_file: - ./laitteiden_saatavuus/.env networks: - database - nginx_network depends_on: - db db: … -
Django multiple image upload but displayed where I tag them
So I can upload Images but I have a problem in which I am putting all my HTML into the TextArea and uploading my images above but I want to display the images where I want on my post instead of some pre-formatted template. So I want my pages to be unique in the layout. Meaning I will want images I upload to be displayed at random point. I'm aware I could hardcode in links but I would rather have Django do it for me. Is there a way in which I can get tags or IDs for the images I upload so I can upload them where I want in the HTML I input into the TextArea -
Django admin shows all the records in the table in a many to many relationship, instead of related fields
So in this project there organizations. Each user can be a manager in multiple organizations. Each user can also be a member of multiple organizations. When I go to the "user page" in django admin (e.g. I click to users and than click to that user), I expect to see a list of organizations that user is a manager, and another list of organizations that user is a member. Instead, for any user, I see a list of ALL the organizations in both the managership and membership list, as in the image below. E.g. the list is not filtered by their user id. What I am doing wrong? How can I fix this? Thanks. My UserAdmin is like: @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = ( ... (_("Managerships"), {"fields": ("managerships", )}), (_("Memberships"), {"fields": ("memberships", )}), ) list_display = ["username", "name", "is_superuser"] search_fields = ["name"] My user model is like this: class User(AbstractUser): ... managerships = models.ManyToManyField(Organization, related_name='managerships',blank=True) memberships = models.ManyToManyField(Organization, related_name='memberships',blank=True) ... And Organization model is like: class Organization(models.Model): name = models.CharField(max_length=200) ... -
Django Selenium functional testing with celery in docker
BACKGROUND: I have a Django application and i want to write tests for it. I have written a docker-compose.yml file so that i can be deployed on server quickly and easily. The application works with the help of celery and redis as its broker. The entire process of selenium testing is also being done via docker where i deploy selenium hub and nodes of chrome and firefox. PROBLEM: When i run the python manage.py test app_name.tests.test_forms my fixtures are loaded and selenium connection is successful, class of the test inherits from StaticLiveServerTestCase. But when i call a celery task from the app_name.tasks.task_name.delay(), obviously after importing it, I noticed that the tasks runs on the my celery worker container that is for the production app and makes the changes that the task is supposed to do in the test database, it does it in the production database. I have tried multiple possible solutions, like adding this above the test class @override_settings(CELERY_TASK_EAGER_PROPAGATES=True,CELERY_TASK_ALWAYS_EAGER=True,BROKER_BACKEND='memory') also tried to starting celery_worker in the test's thread using the following in the setUpClass: cls.celery_worker = start_worker(app,perform_ping_check=False) cls.celery_worker.__enter__() and in tearDownCass: cls.celery_worker.__exit__(None, None, None) and get this following error: ERROR/MainProcess] pidbox command error: AttributeError("'NoneType' object has no attribute 'groups'") … -
To calculate the date in Django
I would like to know how to calculate and print the date in Django. Attached below is model.py. I need to calculate and print out how many days are left based on the date_date of the registered product table. I'd appreciate it if you could tell me how. class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() -
Django export excel file without saving it
Currently I am exporting an excel file, however, before it gets exported, I create an xls file on the host machine. To create the excel file, I use tablib. My export view looks like this: @login_required def export_xls(request): # some irrelevant code data = convert_json_to_dataset(json_data) table = data.export('xls') with open('/tmp/students.xls', 'wb') as f: f.write(table) response = FileResponse(open('/tmp/students.xls', 'rb'), as_attachment=True, filename="test.xls") return response What I am trying to achieve is to avoid writing always to /tmp/students.xls. I tried using BytesIO, however that did not work out. @login_required def export_xls(request): # some irrelevant code data = convert_json_to_dataset(json_data) table = data.export('xls') buffer = BytesIO() buffer.write(table) response = FileResponse(buffer.read(), as_attachment=True, filename="test.xls") return response Currently I am always overwriting the file, however, I will change the naming of the file and that will cause multiple files to be created, which I would like to avoid. -
Create a ChoiceFilter with all the unique values in a specific field (Django)
Say I have a car-model #models.py class Car(models.Model): brand = models.CharField(max_lenght=16) and a user have added the following cars: ["kia","ford","kia","bmw","audi","audi"] I would like to create a filter such that the user has a drop-down (or sort of) with the given brands i.e [kia,for,bmw,audi] to be chosen as a filter. I have tried using the ModelChoiceFilter but that seems to require, a ChoiceField in the model, where the choices are specified, but that is not the case here, since the user is free to write what-ever brand they like. -
Why is my django group showing an empty Queryset
I have this project and I want to be able to allow only members in a particular group to view it. But the problem is that in my admin panel, there are two groups there but when I run request.user.groups.all() I get an empty list? I'm using django 3.2 -
Improper Deep Copy of Model Instance still affecting the Original Instance
I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to make a deep copy of a Movie instance so I can edit the Review objects associated with that instance without those edits affecting the original and being saved to the database. models.py class Movie(models.Model): title = models.CharField(max_length=160) class Review(models.Model): movie = models.ForeignKey(Movie, null=True, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) views.py # Create and save movie object movie = Movie(title="Nightcrawler") movie.save() # Create and save two review objects review1 = Review(movie=movie, author="John", active=True) review2 = Review(movie=movie, author="Rob", active=False) review1.save() review2.save() # Create deep copy of movie instance movie_copy = copy.deepcopy(movie) print("Original before change: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") inactive_reviews = movie_copy.reviews.filter(active=True) print("There are " + str(len(inactive_reviews)) + " inactive reviews.") # Remove inactive reviews from deep copy movie_copy.reviews.remove(*inactive_reviews) print("Deep copy after change: has " + str(len(movie_copy.reviews.all())) + " reviews.") # Check if original movie instance was altered print("Original after change has " + str(len(movie.reviews.all())) + " reviews.") print("Author of the first review is: " + str(movie.reviews.first().author)) The output of the views.py code is as follows: Original before change has 2 reviews. … -
django app listening on localhost:8000 vs 0.0.0.0:8000
I have a Django app running on Google Kubernetes Engine.If I run the enter the pod , and run netstat -l command. It shows that the service is listening on localhost:8000 I ran the same service on Elastic Kubernetes service on AWS. There the service didn't respond to the outside requests when the container was listening on localhost:8000. I had to run python manage.py runserver 0.0.0.0:8000, so that container listens on all the network interfaces. On AWS , the output of netstat -l looks like this I want to understand, that Why the same app was running on the google Kubernetes engine, but not on EKS, and I had to specifically define to listen on 0.0.0.0:8000. Why the google Kubernetes engine listens to outside traffic , when the netstat -l shows that it is listening on localhost:8000 -
Getting error on terminating Django server using Threading and Schedule
I'm trying to use Schedule on the background using threads in my Django application as it was described in Oz123's answer, everything works fine without any problem, except when I'm trying to use commands from the terminal (e.g. python manage.py makemigrations or python manage.py runserver ) they will not end and finished until I'm sending keyboardInterupt. Then it will give me the following error: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 1388, in _shutdown lock.acquire() p.s.: for python manage.py runserver I have to send KeyboardInterupt two times. one for ending the server, then the second one will end the function and raise the mentioned error. My application is using one schedule in the background which is happening every hour to check a model for specific changes. So, there is no stop to this schedule and I want to run it until the server is running (forever). Is there any way to solve this problem? It is so much annoying to press KeyboardInterupt (CTRL + C) for ending every command. -
Change a future date every five days
I am working on a point of sale app in Django in which the customer books a product and it is delivered in 45 days. I can get the delivery date while booking using the following: from datetime import datetime, timedelta DELIVERY_IN_DAYS = 45 delivery_on = datetime.today() + timedelta(days=DELIVERY_IN_DAYS) delivery_on = delivery_on.strftime('%Y-%m-%d') now I want the delivery_on to remain same for 5 days and change on the 6th day. can I do it without using a background celery job? Thanks in advance. -
What's wrong with {% if join_detail.designated_code == element.designated_code %}?
I am a student learning Django. I want to display value_code as follows, but there is a problem that it does not appear. I don't know where the heck is the problem. To represent value_code, designated_code.designated_code is expressed in this way, but all information in the model is not output or output. I want to print only the value corresponding to the if statement. It would be really appreciated if you could tell us what the problem is and how to solve it. Model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # 회원 class Member(AbstractUser): username = models.CharField(primary_key=True, max_length=20, verbose_name='아이디') name = models.CharField(max_length=20, verbose_name='이름', default='') password = models.CharField(max_length=64, verbose_name='비밀번호') phone = models.CharField(max_length=64, verbose_name='전화번호') def __str__(self): return self.username class Meta: verbose_name = ('Member') verbose_name_plural = ('Members') # 카테고리 class Category(models.Model): category_code = models.AutoField(primary_key=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, allow_unicode=True) class Meta: ordering =['category_code'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_in_category', args=[self.slug]) # 상품 class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() … -
Django autocomplete light only works in the admin section
I'm trying to insert the autocomplete in the select to speed up the request. The problem is that it only works in the admin section. Autocomplete in admin section In the user's view, however, it doesn't work at all. Autocomplete not working in user view