Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allowing only the specific users or group of users to visit the specific page of the website in Django?
Let us suppose that there is a admin page in my website designed by me for doing some actions on the website. now i want that only few user that belongs to a specific can visit that page. other users should redirected or should have see an error page when they try to go at that page. for karan(admin ) can visit that page but not ram(simple user) you can also refer any link from the django docs thanks! -
How can I return an image generated in pillow in django without saving in db?
def build_image(image_data): template = Image.open("path/to/file/template.jpg") draw = ImageDraw.Draw(template) draw.text("(553,431)", f"{image_data.text}", fill=4324234, font=font) file = InMemoryUploadedFile(template, None, 'receipt.jpg', 'image/jpeg', template.tell, None) return FileResponse(file, as_attachment=True, filename='receipt.jpeg') I need to return the image that was modified, without saving it to the database. The above code gives the following error: A server error occurred. Please contact the administrator. I also tried the following option: rea_response = HttpResponse(template, content_type='image/png') rea_response['Content-Disposition'] = 'attachment; filename={}'.format('result.png') return rea_response But in this case, I get a corrupted file. (This format is not supported). django==3.0.6 -
How can I create a ForeignKey field only shows when author are current user?
How can I create a ForeignKey field only shows when author are current user? I want to create the admin only show the key that the current user create, and the foreignkey is limit by author is current user, too. models.py class costomize_work_type(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,editable=False,null=True) name = models.CharField(max_length = 10 ) def __str__(self): return self.name class Work(models.Model): name = models.ForeignKey(costomize_work_type, on_delete = models.CASCADE,limit_choices_to={'author': current user}) #other choice author = models.ForeignKey(User,on_delete=models.CASCADE,editable=False,null=True) admin.py class costomize_work_typeAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.author = request.user super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super(costomize_work_typeAdmin, self).get_queryset(request) return qs.filter(author=request.user) admin.site.register(costomize_work_type,costomize_work_typeAdmin) class WorkAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.author = request.user super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super(WorkAdmin, self).get_queryset(request) return qs.filter(author=request.user) admin.site.register(Work,WorkAdmin) -
Upload multiple images from a single button
My goal is to have a single button that a user can upload multiple images from. I implemented a bulk image upload feature from this stack posts top reply. It is somewhat working but instead of a single button it has multiple buttons for image upload How would I go about converting this to a single button that uploads multiple images to be uploaded view: def testing(request): ImageFormSet = modelformset_factory(PostImages, form=ImageForm, extra=1) if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=PostImages.objects.none()) if postForm.is_valid() and formset.is_valid(): testID = postForm.save(commit=False) testID.user = request.user testID.save() for form in formset.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form: image = form['image'] photo = PostImages(post=PostForm, image=image) photo.save() # use django messages framework messages.success(request, "Yeeew, check it out on the home page!") return HttpResponseRedirect("/") else: print(postForm.errors, formset.errors) else: postForm = PostForm() formset = ImageFormSet(queryset=PostImages.objects.none()) return render(request, 'blog/test.html', {'postForm': postForm, 'formset': formset}) template: <form id="postID" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {% for hidden in postForm.hidden_fields %} {{ hidden }} {% endfor %} {% for field in postForm %} {{ field }} <br /> {% endfor %} {{ formset.management_form }} {% for form in formset %} … -
Chaining prefetch_related in reverse Foreign Key queries
This is a follow-up question from this thread. Suppose I have the following 3 models: 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 If I want to fetch specific Seller objects and Genre in one query, I can do this: sellers = Seller.objects.prefetch_related('genre').filter(name__in=['Amazon', 'BarnNoble', Kinokuniya']) Or if I want to fetch specific Genre objects and Book in one query, I can do this: genres= Book.objects.prefetch_related('book').filter(name__in=['Horror', 'Romance', 'Travel']) Is it possible to to chain the two into one single query (albeit a more complex query)? When I tried this: sellers = Seller.objects.prefetch_related('genre').prefetch_related('book').filter(name__in=['Amazon', 'BarnNoble', 'Kinokuniya']) I get the error: Cannot find 'book' on Seller object, 'book' is an invalid parameter to prefetch_related() -
Django management command with dynamic arguments
How would you create a Django management command that has arguments that are dynamic depending on a positional argument? For example, the key value arguments for the command: python manage.py dynamic_command option1 should be different from the arguments for: python manage.py dynamic_command option2 This is useful for cases where the underlying command handle is the same, but parameters could vary depending on the context that the command is run. -
Get the latest UUID created in django model
i want to get the id of the latest entry in a django model, i m using UUID and this query is not working for me it is giving me another id of a fields submitted before that is by some comparaison the biggest. Uploads.objects.latest('id') -
Is it possible to access the value of different tables connected by ForeignKey Django
So I've created a little database relationship for the question: from django.db import models # Create your models here. class Poll(models.Model): title = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title class Option(models.Model): title= models.CharField(max_length=50) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) desc = models.CharField(max_length=255) def __str__(self): return self.title class Voter(models.Model): name = models.CharField(max_length = 255) option = models.ForeignKey(Option, on_delete=models.CASCADE) def __str__(self): return f'{self.name} - {self.option}' So I have 2 questions: Is it possible to access the value of Option model's desc field from Voter model's __str__ function ? Is it possible to access the value of Poll model's date_created field from Voter model's __str__ function ? Thank you so much! -
Django view requests for a specific time period from database
I am developing a project with Django. I want to display the requests from the database in a certain time interval, for example datetime.now() - I want to display the requests 2 minutes ago. Is there a filtering code you can suggest for this? -
could not translate host name "postgres" to address: Unknown host
Setting up a Django project but I am getting a warning about setting up postgres as shown in the title, but I am unsure what this means. Full warning message: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Unknown host And here is how I define postgres in my settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("DB_NAME", "dbname"), "USER": os.environ.get("DB_USER", "dbuser"), "PASSWORD": os.environ.get("DB_PASSWORD", "dbpassword"), "HOST": os.environ.get("DB_HOST", "postgres"), "PORT": os.environ.get("DB_PORT", "5432"), } } Would it possible for someone to walk me through what is going wrong here? I have no idea. -
Djngo How to get GET parameters in template
I'm working on a django project. I'm wondering how to get GET parameters in template so that I can make corresponding tab active. I tried the code below, but it didn't work. <a href="{% url 'blah'%}" class="list-group-item {% if '?q=' in request.path %}active{% endif %}"> lorem ipsum </a> Thank you in advance. -
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.