Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: (1045, 'Plugin caching_sha2_password could not be loaded
I have a django app connecting to mysql. I also use nginx for srving static files. My django app can't connect to mysql that's inside docker. I use docker compose to connect these 3 containers. But when i run docker compose up command i get this error. I use python:3.9-slim-buster image for django app. I already tried chaning it to python:3.9 but nothing has changed. Docker compose file version: '3.8' services: django: build: . volumes: - static:/static - media:/media ports: - 8000:8000 networks: - database environment: DB_HOST: db depends_on: - db nginx: build: ./nginx ports: - 80:80 volumes: - static:/static depends_on: - django db: image: mysql:8.0.25 command: '--default-authentication-plugin=mysql_native_password' restart: always ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: ecommerce networks: - database volumes: - db:/var/lib/mysql volumes: static: media: db: networks: database: Error: Traceback (most recent call last): django_1 | File "/app/manage.py", line 22, in <module> django_1 | main() django_1 | File "/app/manage.py", line 18, in main django_1 | execute_from_command_line(sys.argv) django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line django_1 | utility.execute() django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute django_1 | self.fetch_command(subcommand).run_from_argv(self.argv) django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv django_1 | self.execute(*args, **cmd_options) django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute … -
Possible reasons for Django Channels intermittently functioning
I am attempting to use Django Channels on my digital ocean ubuntu 18 droplet to serve a 'video' feed from a webcam attached to a raspberry pi. The raspberry pi is using python websockets-client and openCV to send jpeg images quickly (every 0.05 seconds). The issue is that this will work great, streaming for 10+ minutes perfectly, and I will think I have got it working. Then the next day, it will stream for about 10 seconds before the raspberry pi disconnects from the websocket from what appears to be my server disconnecting it, and then I cannot get it to stream longer than a few seconds. Why would it work perfectly one day, and not the next? Nothing obvious has changed. The reason I think it is my server/channels/redis causing the problem: Before the raspberry pi even seems to be having any trouble, the video feed being shown on the browser will become very laggy then will stop getting new images entirely. Then a few seconds later my raspberry pi socket will disconnect from the websocket. What I have Tried: I have done a speed test on my internet connection and it is 50mb down/15mb up. I have tried … -
Field 'id' expected a number but got 'hellooo' - Django Blog Comments
I'm trying to make it possible to add comments on my blog, but I'm getting the following error when I try to submit the comment: "Field 'id' expected a number but got 'hellooo'." Views.py: class AddComment(generic.CreateView): model = Comment form_class = AddComment template_name = 'add_comment.html' def form_valid(self, form): form.instance.post_id = self.kwargs['slug'] return super().form_valid(form) success_url = reverse_lazy('blog') forms.py: class AddComment(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') widgets = { 'Name': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } models.py: class Comment(models.Model): post = models.ForeignKey(Post, on_delete= models.CASCADE, related_name='comments') name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) urls.py: from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='blog'), path('add_post/', views.AddPost.as_view(), name='add_post'), path('edit_post/<slug:slug>/', views.EditPost.as_view(), name='edit_post'), path('delete_post/<slug:slug>/', views.DeletePost.as_view(), name='delete_post'), path('<slug:slug>/comment/', views.AddComment.as_view(), name='add_comment'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] -
Django: Get first row from related table and show with main table query
The image table contains multiple images of a product. I want to bring an image column to match the product ID in the query set of the product table, which is the first image of the related product ID in the image table. Model: class Product(models.Model): product_code = models.CharField(max_length=50, unique=True) product = models.CharField(max_length=100, unique=True) class Image(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='images') Raw SQL: select p.*, i.image from accpack_product p join (select product_id, image from accpack_image group by product_id order by id) i on p.id=i.product_id order by p.id -
Django app import models form another file not working
Hi I am having a problem with importing a model form another app file that I have in the same project. -DND_website -data -__init__.py -models.py -main -views.py the code: from DND_website.data.models import PagesData error: ModuleNotFoundError: No module named 'DND_website.data' -
Jquery append method returning html tags instead of the proper formats
The feature is for a quiz and im retrieving the data for the quiz that is the questions and answers and appending it to my div having id test_box. The data has been successfully retrieved but instead of proper formatting the data, it is returning me in form of html tags. Here is my code snippet: const url = window.location.href const testBox = document.getElementById('test_box') $.ajax({ type: 'GET', url: `${url}/data`, success: function(response){ const data = response.data data.forEach(element => { for (const [question, answers] of Object.entries(element)){ testBox.append(` <div class="question_box"> <div> <b>${question}</b> </div> `); answers.forEach(answer => { testBox.append(` <div> <input type="radio" class="ans" id=${question}-${answer}" name="${question}" value="${answer}"> <label for="${question}">${answer}</label> </div> `) }) testBox.append(`</div>`); } }); }, error: function(error){ console.log(error) } }); -
getting module not found "ModuleNotFoundError at /" Herokuapp Django
I and getting the below on Heroku Sub domain - https://icoder-django.herokuapp.com/ ModuleNotFoundError at / No module named 'blog.urls' requirements.txt asgiref==3.3.4 dj-database-url==0.5.0 Django==3.2 django-cors-headers==3.7.0 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.8.6 python-decouple==3.4 pytz==2021.1 sqlparse==0.4.1 whhitenoise==5.2.0 Error in web page ModuleNotFoundError at / No module named 'blog.urls' Request Method: GET Request URL: https://icoder-django.herokuapp.com/ Django Version: 3.2 Exception Type: ModuleNotFoundError Exception Value: No module named 'blog.urls' Exception Location: <frozen importlib._bootstrap>, line 984, in _find_and_load_unlocked Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] and this as well /app/iCoder/urls.py, line 26, in <module> admin.site.site_header = "iCoder Admin" admin.site.site_title = "iCoder Admin Panel" admin.site.index_title = "Welcome to iCoder Admin Panel" urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), … ] ▶ Local vars -
Django/Local Library. How to assign current user to field?
I've started learning Django and im doing a local library. I have a problem. I've created a model Book, which has a borrower. When I want to save current user as a borrower value changes only on page, but not in admin panel. It also changes every single books' value, not just the specific one. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=60) ISBN = models.CharField(max_length=13,unique=True) genre = models.ForeignKey(Gatunek,related_name='Books',on_delete=models.PROTECT) borrower = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default='') def __str__(self): return self.nazwa class BookRent(ListView): model = Book template_name = "Books/Book_rent.html" def get_queryset(self): user = self.request.user Book.borrower = user -
Is it possible to customize django.auth error message appropriate for certain registration errors?
I'm trying to display an error message for a certain error that user makes while registering, for now I've only covered an error regarding password and conf_passowrd not matching, but only that scenario works, whenever there is an error regarding, for example, too short password entered, it still displays the error regarding password mismatch. What I've tried so far: view.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def indexsignup(request): form = UserCreationForm() if request.method == 'POST': regForm = UserCreationForm(request.POST) if regForm.is_valid(): regForm.save() return redirect('login') else: for msg in form.error_messages: if len('password1') < 6: messages.error(request, f"PAss short") print(msg) else: messages.error(request, f"Two passwords don't match.") print(msg) return render(request, 'registration/register.html', {'form':form}) register.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Forum - SignUp</title> <link rel="stylesheet" href="{% static 'signup/style.css' %}"> </head> <body> <div class="signin-box"> <h1> Sign Up</h1> <form method="post" action=""> {% csrf_token %} <div class="textbox"> <input type="text" name="username" placeholder="Username" maxlength="10" autocapitalize="none" autocomplete="username" autofocus="" required="" id="id_username"> </div> <div class="textbox"> <input type="password" name="password1" placeholder="Password" autocomplete="new-password" required="" id="id_password1"> <script type="text/javascript"> function reveal() { if (document.getElementById('box').checked) { document.getElementById("id_password1").type = 'text'; } else document.getElementById("id_password1").type = 'password'; } </script> <div class="check"> <input title="Reveal password" type="checkbox" id="box" onclick="reveal()"> </div> </div> <div class="textbox"> <input … -
How to save videos and files as udemy, only those who bought the course can access and download the course videos and files
How to save videos and files as udemy, only those who bought the course can access and download the course videos and files in django i mean save my viedos and files private -
TypeError: a bytes-like object is required, not '_io.BytesIO' | Django | Pillow
I have been working one a Django project and I need to save an image file manually. So, I tried using PIL. Here's the code in my Django view that breaks- import PIL.Image as PilImage image_file = request.FILES.get("pic").file image = PilImage.open(io.BytesIO(image_file)) I don't understand it because io.BytesIO is a byte-like object, right? I couldn't find any solution anywhere so I'd appreciate any help. The full error is below - Traceback (most recent call last): File "G:\Workspace\Rabo\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "G:\Workspace\Rabo\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Workspace\Rabo\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "G:\Workspace\Rabo\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "G:\Workspace\Rabo\App\utils\login_required.py", line 25, in wrapper return f(self, request, user_id) File "G:\Workspace\Rabo\App\views\user_views.py", line 125, in post image = PilImage.open(io.BytesIO(image_file)) TypeError: a bytes-like object is required, not '_io.BytesIO' -
how to create new tag or select from current tags using Django forms
I have 3 tables, Products, Articles, and tags products and articles both have a "tags" field which has ManyToMany relation with the "tags" table I want to be able to reference multiple tags or create new tags while adding a product or an article (in one field)(using Django forms) for example, "test1" and "test2" are already in the tags table, I want the field to be like this: 1.I type "te" in the tags field 2.A drop down with "test1" and "test2" is opened which I can choose each one of them to be added in the field 3.I type "test3" (which isn't already in the tags table)and hit enter and "test3" is added to the field products and articles both have a "tags" field which has ManyToMany relation with the "tags" table (just like tags in a post in StackOverflow) I think Django built-in forms can handle this but I'm overwhelmed by the documentation and lost in the configuration of my Django forms. what kind of fields and widgets should I use for this purpose? Excuse me if the question is vague I'm new to Django and I would appreciate any kind of help. -
Django UpdateView returns a blank rendered template
I am using django allauth for user authentication, in my adapter I have modified the get_login_redirect_url to redirect new users to an ONBOARD_URL so they can complete registration process while regular users get the expected LOGIN_REDIRECT_URL class UserAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): if request.user.is_authenticated and (not request.user.name or not request.user.avatar or not request.user.mobile): url = settings.ONBOARD_URL else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) I have two functions handling the view and they both inherit from UpdateView and DetailView respectively. class UpdateUserAfterSignupView(LoginRequiredMixin, UpdateView): model = User form_class = UpdateUserAfterSignupForm template_name = 'users/user_form.html' context_object_name = 'user' success_url = reverse_lazy('users:detail') class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = 'username' slug_url_kwarg = 'username' template_name = 'users/user_detail.html' context_object_name = 'user' def get_object(self, queryset=None): return get_object_or_404(self.model, username=self.request.user.username) In my DetailView, if i leave out the get_object it returns a PageNotFound 404, but when its present as is, I get a blank page in the rendered template. This is the template: <p>welcome {{user}}</p> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" value="submit">submit</button> </form> and my url conf looks like this [ path('<str:username>/', views.UserDetailView.as_view(), name='detail'), path('complete-signup/', views.UpdateUserAfterSignupView.as_view(), name='complete_signup'), ] Again, all of these results in a blank rendered template, nothing at all. Could you please suggest things … -
Django queryset to string does not return the string in a test
I'm trying to write a unit test for this model: ADMIN = 1 FULL_USER = 2 LIMITED_USER = 3 class Role(models.Model): """ The class stores the model to store the different role which will be used to assign permissions to the users. """ ROLE_CHOICES = ( (ADMIN, 'admin'), (FULL_USER, 'full_user'), (LIMITED_USER, 'limited_user') ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) name = models.CharField('name', max_length=30) def __str__(self): """String for representing the Model object.""" if self.name: return self.name return self.id So I wrote this test: from example.models import Role from rest_framework.test import APITestCase class RoleModel(APITestCase): fixtures = ["initial_data/role.json"] def test_get_admin_role(self): role = Role.objects.filter(id=1) self.assertEqual(str(role), 'admin') But I'm not able to understand why it fails with this: AssertionError: '<QuerySet [<Role: admin>]>' != 'admin' - <QuerySet [<Role: admin>]> + admin I have read similar questions on how to get the string of the queryset and it should be the one defined in __str__. but I don't know why it is surrounded by <QuerySet [<Role: HERE_IS_MY_STRING]> if I'm asking for the string representation of the object. -
I need help. I am hosting site first time in my life. I want to deploy my Django site on AWS
when I will deploy the website at that time virtual env folder will helpful or only the requirement.txt file will enough. -
Dajngo: Get the ID of a clicked button
I am using django. In my views I want to know which button was pressed. My template.html looks like: {% for post in posts %} <button name="{{ post.pk }}" type="submit">{{ post.title }}</button> {% endfor %} I know that in my views.py I can check if button x was pressed by just: if '12345' in request.POST: # do something elif '23456' in request.POST: #do something else But is there a way to get the primary key without checking every key possible? I would love something like this: #PSEUDOCODE post_primary_key = request.POST.get_name() If my approach is fundamentally bad, I am also open to alternative ways of solving my problem. -
How to debug django-select2 dropdown
Id like to create a text search field based on dropdown options from a model. I chose on django-select2 but it isn't working. This is the output html <form class="add_new container" method="post"> <h3 class="text-center">Issue Book</h3><hr><br> {% csrf_token %} <h4> Choose the student to issue book to</h4><br> {% for field in form %} {{ field }} {% endfor %}<hr><br> <input type="submit" value="Issue" class="btn btn-dark text-right" style="float:right"> </form> This is the form class NewIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['borrower_id'].queryset = Student.objects.filter(school=school) self.fields['book_id'].initial = pk #Sets the field with the pk and it's hidden again class Meta: model = Issue fields = ['issuer','book_id','borrower_id'] widgets = { } widgets = { 'book_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'borrower_id': Select2Widget, } Settings.py hs the following CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } -
Digital Ocean Forbidden You don't have permission to access this resource
I am using Django I do not know how to setup config file ''' Alias /static root/pixlfy/googlesheet/static <Directory root/pixlfy/googlesheet/static> Require all granted <Directory root/pixlfy/googlesheet/googlesheet> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess pixlfy python-home=root/pixlfy/projectenv python-path=root/pixlfy/googlesheet WSGIProcessGroup pixlfy WSGIScriptAlias / root/pixlfy/googlesheet/googlesheet/wsgi.py <Directory root/pixlfy/googlesheet/googlesheet> Order allow,deny Allow from all </Directory> ''' -
Django template variable not rendering
So I am trying to render a django template variable, but for some reason it is not rendering out. I have the following code: Views.py ... def get_search(request, *args, **kwargs): context = {} context = {"test":"abcde"} return render(request, 'search.html', context) ... Urls.py urlpatterns = [ path("", home_view), path("articles/", include("papers.urls")), path("admin/", admin.site.urls), path("search/", search_view), path("submit/", submit_article_view, name="submit"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) search.html {extends 'base.html'} {% block content %} <p> {{ test }} hi </p> ... {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>Title</title> <link rel="stylesheet" type ="text/css" href="{% static 'css/stylesheet.css' %}"> </head> <header> {% include 'navbar.html' %} </header> <body> {% block content %} {% endblock %} </body> <footer> {% include 'footer.html' %} </footer> </html> Now, whenever I run the server and go to the search page, everything else gets rendered out, but the {{ test }} doesn't. The 'hi' does get rendered out. I have followed every tutorial and StackOverflow question out there, to no avail. Anyone has any idea what might be going on? Also, StackOverflow newbie, let me know if I did something wrong regarding that :). -
how do I take files from local file system (django) and render it to the frontend (react)
I am currently working on a web application which will only run on my machine. I want django to access my local file system using a python script and then send it to the react front-end in which it can be shown to the user. Is this possible? I can find no information on this except that django can access files from the media and static directories only. -
creating sidebar in django using CSS but appears nothing
i was trying to create sidebar base on codewithtim however it appears that it didn't read any of the css code below is my home.html: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <style type="text/css"> .sideenv a{ padding: 6px 8px 6px 18px; text-decoration: none; font-size: 25px; color: : #818181; display: block; } </style> <title>{% block title %}home{% endblock %}</title> </head> <body> <div class="sidenav"> <a href="">home</a> <a href="/vendor">vendor</a> <a href="/search">search</a> </div> </body> {% endblock %} and here is my base.html: <!doctype html> <html> <head> <title>{% block title %}prototype{% endblock %}</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> </head> <body> <!--{% include 'navbar.html' %}--> {% block content %} replace me {% endblock %} </body> </html> The only thing different from my code than codewithtime is i am trying to use block content to override some bolck. it might be wrong here, but i have no idea how to correct it ================================================================== And i have another question about using css in django when i google "css in django" usually the doc shows code below <head> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Linguist</title> </head> why did codewithtim can ignore the implementation and just include css might … -
ModuleNotFoundError: No module named 'xxxx.yyy'
I am very new to python programing and django.. I have not found any resources addressing this issue on web hence reaching out community. I have a django rest api with following code MyApi.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class MyOwnView(APIView): def get(self, request): return Response({'some': 'data'}) My module is not found in the url.py file, below is url.py file And urls.py file is here: from django.contrib import admin from django.urls import path from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User from jpbapi.api.MyApi import MyOwnView urlpatterns = [ path('admin/', admin.site.urls), ] This fails loading my module please see my project structure below, not sure where i am wrong. -
Is there a way in Django to unlock the resources before the transaction is over or to auto restart the transaction if the deadlock is found?
I have a model Orders in my Django rest-framework app. I am retrieving a list of orders based on some filter parameters and at the same time I am also locking orders using select_for_update(). Each order in the Orders model has a status and it could be OPEN, PARTIALLY_COMPLETED, COMPLETED or CANCELLED. However, one of my filter parameters will only consider the order with status OPEN or PARTIALLY_COMPLETED. So the retrieved list will have order with OPEN or PARTIALLY_COMPLETED status only. Furthermore, each order in Orders model also has the parameter units. This represents the units at which the order was created. If the order is in OPEN state then all the units are unsold or if the order is in PARTIALLY_COMPLETED then unsold_units = units - sold_units. Deriving the unsold units for PARTIALLY_COMPLETED orders is done after retrieving the list of orders. Now, let's assume the retrieved order list has 10 order and the total of unsold_units of the list is 1000. However, I just need 100 units so if the unsold_units of the first 3 orders is equal or over 100 units than the remaining orders must be unlocked immediately so that the other transaction can use it. … -
'int' object has no attribute 'user_list'. (Django Rest Framework)
I have a feature where user can remove an item from a list. The code below does successfully remove (delete) the item from the list but also returns the following error (and my AJAX call doesn't complete successfully): Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'user_list'. I am not sure how to debug this/why this error is being thrown. Here is my serializers: class UserVenueSerializer(serializers.ModelSerializer): venue = mapCafesSerializer() class Meta: model = UserVenue fields = ['user_list', 'venue'] Here is my views class RemoveVenueViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserVenueSerializer authentication_classes = [CsrfExemptSession] def get_queryset(self): user_list = self.request.GET.get('user_list', None) venue = self.request.GET.get('venue', None) data = UserVenue.objects.filter(user_list = user_list, venue= venue) print(data) return data.delete() Here is the traceback: <QuerySet [<UserVenue: UserVenue object (142)>]> Internal Server Error: /api/removevenue/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'int' object has no attribute 'user_list' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Order a queryset by a field in another queryset
In my django blog app, I have a model for Bookmark, which includes fields pointing to Post and User, and a field for when the bookmark was created. # models class Post(models.Model): # ... title = models.CharField(max_length=70) body = RichTextField() author = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name='posts') created_on = models.DateTimeField(default=timezone.now) # ... class Meta: ordering = ['created_on'] class Bookmark(models.Model): post = models.ForeignKey( Post, on_delete=CASCADE, related_name="bookmarked_post" ) user = models.ForeignKey( User, on_delete=CASCADE, related_name="bookmarks" ) created_on = models.DateTimeField(default=timezone.now) class Meta: ordering = ['created_on'] I have a view to display my users' bookmarks. I want to order the posts queryset in the order they were bookmarked, with the recently bookmarked posts first. # views.py @login_required def bookmarks_view(request): bookmarks = Bookmark.objects.filter(user=request.user) bookmarked_posts = Post.objects.filter( bookmarked_post__in=bookmarks).order_by(???) return render(request, 'bookmarks.html', posts=bookmarked_posts) I'm struggling to figure out how to order my Posts queryset by the created_on field in the Bookmark model. To add additional complexity, both the Post and Bookmark model have a created_on field. Can anyone point me in the right direction with this? I've scoured the django documentation and SO and not finding what I need, possibly I just don't know the right keywords... Or have I set up my models incorrectly to achieve what I …