Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pulling the most recent data from underlying table in Django
I'm new to Django and don't have much experience in coding. I'm a bit confused about how it actually talks to databases. I'm trying to take a stab at building a dashboard that will display a table. The data comes from an Oracle database, and the table I'm particularly interested in is being constantly updated outside of Django. It's a living object and I would like the dashboard to display the "current state" of that table on page load. My understanding is that Django models will not help here because what Django displays is the state the table has been in during the last migration/sync, correct? Am I stuck with raw sql then? Is there even a point in creating models in this case? On top of that I would love to be able to update/delete rows in the table from the dashboard itself but I'm not sure how to do that when the underlying Oracle table is changing every couple of minutes. Am I thinking about this incorrectly? Thanks! -
Syntax to reverse-query a cached queryset
I have the following 3 models related by Foreign Key as following: class Seller(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Genre(models.Model): seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name And I want to retrieve the whole 3 tables in one database query, by querying the Seller objects, as following: sellers = Seller.objects.select_related('genre', 'book').all().values('name') seller_df = pd.DataFrame(list(sellers)) What is the syntax to filter for books carried by a particular seller, without hitting the database again: seller1 = seller_df ['name'].iloc[0] seller1_books = Book.objects.filter(...) seller_last = seller_df ['name'].iloc[-1] seller_last_books = Book.objects.filter(...) -
How to have Django view with variable amount of forms?
Before I jump into this, I want to know if there is one best way to do this. Let's start from the beginning. I have 3 models, Recipe, Ingredient, and Step. Their models are set up like this: class Recipe(models.Model): prep_time_choices=[ ('short', 'Short (>20m)'), ('medium', 'Medium (20m-1h'), ('long', 'Long (<1h)') ] difficulty_choices=[ ('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard') ] name=models.CharField(max_length=20, help_text='Enter the name of this recipe') description=models.TextField(max_length=75, help_text='Describe your recipe') date=models.DateTimeField(default=timezone.now) prep_time=models.CharField(max_length=6, choices=prep_time_choices, default='short') difficulty = models.CharField(max_length=6, choices=difficulty_choices, default='easy') servings=models.IntegerField() author= models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name return self.prep_time def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk}) class Meta: ordering = ['-date'] class Ingredient(models.Model): recipe=models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient=models.CharField(max_length=100) class Meta: ordering = ['ingredient'] def __str__(self): return self.ingredient class Step(models.Model): recipe=models.ForeignKey(Recipe, on_delete=models.CASCADE) step=models.TextField(max_length=750) number = models.IntegerField() class Meta: ordering = ['number'] def __str__(self): return f'{self.recipe.name}: {self.number}' What I want to do is create a create view, that allows a user to create 1 Recipe, variable amount of ingredients and, variable amount of steps, presumably adding inputs using JavaScript. Ideally, it'd be as simple as just making a class based view and making it inherit from Django's builtin CreateView, however, as far as I know, that only works for one model. Can anyone help? -
Display an image from a URL in Django
I am creating a webpage in Django. In a Django form I would like a user to be able to provide an image using a URL. I need to save this information and render this image in a html. How should I do this? -
How to filter Django REST Framework queryset by foreign key of nested object?
I have the following Django models: class Pa(models.Model): pa_name = models.CharField class Pb(models.Model): pa = models.ForeignKey(Pa, related_name="pbs") pb_name = models.CharField() class Pc(models.Model): pb = models.ForeignKey(Pb, related_name="pcs") pc_name = models.CharField() The queryset of Pc has this structure: [ { "id": 1, "pc_name": "pc_1", "pb" = { "id": 10, "pb_name": "pb_1", "pa" : { "pa_name" : "pa_1" # <-- How to filter queryset by pa_name attribute? } } }, { "id": 2, "pc_name": "pc_2", "pb" = { "id": 20, "pb_name": "pb_2", "pa" : { "pa_name" : "pa_2" } } }, # ... ] I'd like to return all those Pcs, where pa_name is "pa_1", i.e. filter over the 2. level nested object. -
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. …