Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CreateView not working with custom auth model
I have a simple application with a very simple custom user auth model and base manager. When I try to create a user using CreateView, I get no errors and no user entries are made in the database. Here is what I have. models.py: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.db import models class AccountManager(BaseUserManager): def create_user(self, email, username, password, **other_fields): .... .... email = self.normalize_email(email) user = self.model(username=username, email=email, **other_fields) user.set_password(password) user.save() def create_superuser(self, email, username, password, **other_fields): .... return self.create_user(email, username, password, **other_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(default=timezone.now) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username Here is my forms.py: class CreateUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): # If it's a checkbox, add form-check-input css class, else form-control class if visible.field.widget.__class__.__name__ == forms.CheckboxInput().__class__.__name__: visible.field.widget.attrs['class'] = 'form-check-input' else: visible.field.widget.attrs['class'] = 'form-control' class Meta: model = get_user_model() fields = ('username', 'email', 'password') And here is how I am calling the form in views.py: … -
Celery encoder error with django rest framework
I am using Celery - Redis - Django rest framework together. The error happens when I try to pass the serializer to the delay of celery within the Django rest framework. Here is the viewset class TestSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = ImageSerializer def create(self, request, *args, **kwargs): serializer = TestSerializer(data=request.data) if serializer.is_valid(): print("I AM HERE") <-- This prints out result = test_call.delay(serializer) <-- The error happens here data = {"task": result.task_id} return Response(data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @shared_task(name="values") def test_call(serializer): ..some logic return serializer The error I get is kombu.exceptions.EncodeError: Object of type ImageSerializer is not JSON serializable I have the following in settings.py CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' -
Testing admin custom action with form
I am developing a small django project to help administrate my dance school(my hobby) So the app has some courses and for each course has many classes or lessons. in the django admin in the course_changelist url i added a custom action create lesson with a custom form CreateLessonsDatesForm with 2 charfield a start_date and a end_date. This actions basically create a lesson of that course. So for example if the course is on weekly basis every Wednesday, the action will automatically create a lesson of that course every Wednesday from the start date until the end date The action works fine on browser but when tested it doesn't create any lesson. I create a second action "prova" just to double check, it simply change the vowels of the place field in all i, without passing any form value, and it works. So probably i am missing something when using the form with the tests. Thanks a lot here's the code: #core/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin from django.utils.translation import gettext as _ class Course(models.Model): """ Blueprint course it contain information about what style is taught, the time and place and the frequency """ … -
Use to_representation to combine fields from related models in Django Rest Framework
I've got the following models:- class Player(models.Model): first_name = models.CharField() etc. class Game(models.Model): date = models.DateField() etc. class GameMembership(models.Model): player = models.ForeignKey(Player, related_name="memberships") game = models.ForeignKey(Game, related_name="memberships") available = models.BooleanField(default=False) I've created a ModelViewSet to return all the Players but I'd like to be able to, for each player in the list, return a list of their game memberships. I can do that, quite easily, but the data it returns looks like this:- { "id": "1", "memberships": [ { "available": True, "game": { "date": "a date", etc. } }, { "available": False, "game": { "date": "a date", etc. } } ] } but I'd like to hide the "memberships" aspect of my database from the API users and return something like this instead:- { "id": "1", "games": [ { "available": True, "date": "a date", etc. }, { "available": False, "date": "a date", etc. } ] }, So I want to take a field (or two) from the GameMembership model and combine it with all the fields from the Game model but crucially, I want it all in to one dictionary in the returned results. I know I can simply serialize Game on the GameMembershipSerializer, but that means that I'll be … -
Axios post request to send file using form data in Typescript
I want to send the file from typescript to Django. But Server response content-length=''. But it work well when I send a file using POSTMAN. What am I doing wrong? const form = new FormData(); form.append('file',fs.createReadStream(file_path)); axios.post(URL, form , {headers: form.getHeaders()} ) .then(res => { console.log(`statusCode: ${res.status}`); console.log(res); }) .catch(error => { console.error(error); }) Server (django) class IndexView(View): def post(self, request): print(request.headers) print(request.body) print(request.FILES) Result {'Content-Length': '', 'Content-Type': 'multipart/form-data; boundary=--------------------------630438350591138162261166', 'Host': 'URL', 'User-Agent': 'axios/ 0.24.0', 'Transfer-Encoding': 'chunked', 'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip', 'X-App': 'go-proxy', 'X-Forwarded-For': '10.1.20.116, 10.1.20.239'} b'' <MultiValueDict: {}> -
Show DB content in template sorted by date
I'm currently showing the content in the template ordered by sequence_number #models: class FlowPhase(models.Model): sequence_number = models.IntegerField(validators=[MinValueValidator(1)]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) #viewset # Function to define sort criteria def take_seq_number(elem): return elem['flow_phase']['sequence_number'] def phase_details(request, batch_pk): ph_details_url = API_HOST + "/api/phase_details_full/?batch=" + str(batch_pk) answer = requests.get(ph_details_url).json() if 'results' not in answer: return HttpResponse('<h1>Could not retrieve phase details.</h1>') ph_details = answer['results'] if len(ph_details) == 0: return HttpResponse('<h1>No phase associated to this batch.</h1>') ph_details.sort(key=take_seq_number) # <------ sorting by sequence number rendered_page = render(request, 'batches_phases/consumer/phase_details.html', {'ph_details': ph_details}) return rendered_page So, I want to show the content of ph_details in the template ordered by updated_at and not by sequence_number anymore. Any suggestions on how to do this in python? In this case, I believe that the changes would only be in ph_details.sort(key=take_seq_number) and def take_seq_number(elem): return elem['flow_phase']['sequence_number'] My difficulty is that since sequence_number is integer, it's easier to sort. But how to do this with dates? -
infinite scroll working but not doing things as it should
in my web site i want to show the user ratings for that i used the infinite scroll but i am facing one problem. when it first loads the data before calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is showing the star with the count of vote,but when after calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is not showing the star. my views.py @login_required def ratings_user(request,pk): ratings = VoteUser.objects.filter(the_user_id=pk).order_by('-pk') paginator = Paginator(ratings, 1) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,request.session['is_mobile']+'profile/ratings.html',{'ratings':posts}) html {% extends 'mobile/profile/base.html' %} {% load static %} {% load crispy_forms_tags %} {% load get_companion %} {% load cache %} {% block title %} Ratings {% endblock %} {% block leftcontent %} <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"> {% endblock %} {% block middlecontent %} <div class="infinite-container"> {% for i in ratings %} <div class="infinite-item"> <div class="w3-container w3-card w3-white w3-round w3-margin"> <img src="{{ i.the_user.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:40px;height:40px;border-radius:50%;"> <a href ="{% url 'profile' i.the_user_id %}" style="color:black;">{% with user=i.the_user.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}</a> <br> <span class="stars" data-rating="{{ i.vote.vote }}" data-num-stars="5" ></span> <hr class="w3-clear"> <p> {{ i.commentaire|linebreaksbr }} </p> <span class="glyphicon glyphicon-user"></span> <a href … -
populate text field based on dropdownlist selection in django models
I have a dropdown list named car_model. I bind it with my t_cars model. What I wanted to happen is, when I choose a car model, the textboxes will be populated with the other car attributes from my car model. Like for example, (sample table) Model=Toyota Price=$2500 Color=Red Model=Nissan Price=$3000 Color=Orange When I select Toyota, the textboxes will be populated with the color and price of the car model Toyota which is $2500 and color orange. I'm sorry for having a hard time explaining it. I hope that someone can help me with this. Here are my codes. models.py class t_cars(models.Model): c_model=models.TextField("Model",max_length=25, blank=True, null=True) c_price=models.FloatField("Price",blank=True, null=True) c_lot=models.TextField("Color",max_length=25, blank=True, null=True) views.py def createCars(request): cars=t_cars.objects.all() context={'cars':cars} return render(request, 'accounts/cars_form.html', context) car_form.html <div> <label>Car Model:</label> <select id='car_model' name='car_model' type="text" onchange="populateTxtBox(this)"> {% for c in car %} <option>{{ c.c_model }}</option> {% endfor %} </select> </div> <label><b>Price: </b></label> <input id='car_price' name='car_price' type="text"> <label><b>Color: </b></label> <input id='car_color' name='car_color' type="text"> script In my script, I'm only trying to show the price first before I proceed to car color but it does not working. function populateTxtBox(){ var model = document.getElementById("car_model"); var selectedOption = model.selectedOption[model.selectedIndex].value; var price=document.getElementById('car_price'); price.value=selectedOption; } -
How to return multiple variables in celery?
The error I get is TypeError: cannot unpack non-iterable AsyncResult object The function is from celery import shared_task @shared_task(name="values", trail=True) def simple(x,y): return x,y x, y = simple.delay(1,2) -
I need people who are confident about Django,I need Help ,Thank you
I have researcing from 3 weeks, but ı couldnt any solution about my problem Can Someone help me, ı severe I will pray for him, I m trying to create an User model and a CellingTable in Django, I created.. but there is a little nightmate in my mind.. user has a local wallet like " user_balance" , user will buy something from "Product Table", Product Table already has priceses by the way, Thats Products( user bought) prices sum, Should be fall from the "user_balance". But I couldnt any example or advice about that stiation. I know Maybe that problem so easy. But again ı know, we guys so perfect for helping eachother. I hope u guys can help me, if u guys help me ı can learn , but no ones dont help eachother, no ones can learn Thank u for ur attention and helping, Good afternoon, Good Evening and Good Night :) -
Large video file upload(like 2gb) in chunk by chunk and add those chunk to get the original file using javascript ajax and django without any api call
My views.py file like this Now I have some problem to stich all the chunks into the file in views.py and also take so much time to upload this video file.Please help. This file upload need to ajax form submit, here I am taking the file and slice it into some specific size of chunk and then send that chunk to our video_upload method. def video_upload(request): video_upload_response = [] curr_time = time.localtime() curr_clock = time.strftime("%H:%M:%S", curr_time) if request.method == 'POST': form = VideosForm(request.POST, request.FILES) if form.is_valid(): course_id = request.POST.get("course_id") print(course_id) video_title = request.POST.get("video_title") print(video_title) video_file_name = request.POST.get("video_file_name") print(video_file_name) video_file = request.FILES['video_file'] # print(list(video_file)) chunk_data = request.POST.get("chunk_data") print(type(chunk_data)) print(curr_clock) if chunk_data == 'null': print("ok") else: chunk_data = bytes(chunk_data, 'ascii') print("hhhhhh") print(type(chunk_data)) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/media" file = open(os.path.join(BASE_DIR, video_file_name), 'wb+') file.write(chunk_data) return JsonResponse(video_upload_response, safe=False) (function($) { var reader = {}; var file = {}; var slice_size = 10485760; $(document).on('click', '.video_form_submit', function(event){ form_id = $(this).data("form-id") // console.log(form_id) course_id = $(this).data("course-id") // console.log(course_id) video_title = $("#video_title_"+form_id).val() file = $("#video_id_"+form_id)[0].files[0] csrf_token = $(this).data("csrf-token") $("#progress_process_"+form_id).css('display', 'block'); $("#progress-bar1_"+form_id).css("width", "0%"); $("#progress-text1_"+form_id).html("0 %"); start_upload(event, file, csrf_token, course_id, video_title, form_id); }); function start_upload(event, file, csrf_token, course_id, video_title, form_id) { event.preventDefault(); reader = new FileReader(); file = file console.log(file) upload_file(0, csrf_token, … -
Django: Return id of maximum value where grouped by foreign key
Information I have two models: class BookingModel(models.Model): [..fields..] class BookingComponentModel(models.Model): STATUS_CHOICES = ['In Progress','Completed','Not Started','Incomplete','Filled','Partially Filled','Cancelled'] STATUS_CHOICES = [(choice,choice) for choice in STATUS_CHOICES] COMPONENT_CHOICES = ['Test','Soak'] COMPONENT_CHOICES = [(choice,choice) for choice in COMPONENT_CHOICES] booking = models.ForeignKey(BookingModel, on_delete=models.CASCADE, null=True, blank=True) component_type = models.CharField(max_length=20, choices=COMPONENT_CHOICES) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='Not Started') order = models.IntegerField(unique=True) [..fields..] What I want I want to get the booking component for each booking which has the last value (maximum) in order. It will also need to have a status='In Progress' and component_type='Soak'. For example for table: +----+------------+----------------+-------------+-------+ | id | booking_id | component_type | status | order | +----+------------+----------------+-------------+-------+ | 1 | 1 | Test | Completed | 1 | +----+------------+----------------+-------------+-------+ | 2 | 1 | Soak | Completed | 2 | +----+------------+----------------+-------------+-------+ | 3 | 1 | Soak | In Progress | 3 | +----+------------+----------------+-------------+-------+ | 4 | 2 | Test | Completed | 1 | +----+------------+----------------+-------------+-------+ | 5 | 2 | Soak | In Progress | 2 | +----+------------+----------------+-------------+-------+ | 6 | 3 | Test | In Progress | 1 | +----+------------+----------------+-------------+-------+ Expected outcome would be id's: 4 & 6 What I've tried I've tried the following: BookingComponentModel.objects.values('booking').annotate(max_order=Max('order')).order_by('-booking') This doesn't include the filtering but returns … -
Django FormModel map fields to HTML Form
I have forms created on my Django site, they have been manually created using HTML and then using JavaScript to POST the form content to the model. Now I am working on updates to the model. I've taken the existing HTML form for the page, but I can't work out how I map the view fields to the HTML form? Views.py def update_event(request,event_id): event = Event.objects.get(pk=event_id) form = addEventForm(request.POST or None, instance=event) return render(request, 'pages/update_event.html', {'event': event, form : form}) models.py class Event(models.Model): project = models.ForeignKey(Game, to_field='project_name', on_delete=models.CASCADE) event_name = models.CharField(max_length=20) event_date = models.DateTimeField(blank=True, null=True) def __str__(self): return str(self.event_name) HTML <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="event-name-label">Event Name</label> <input type="text" class="form-control" id="event-name" value="" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please fill Event name. </div> </div> </div> I've tried using form.event_name but this doesn't work. Any help would be great Thanks -
Django select from multiple models
What is the best way to select data from multiple models? For example class User(models.Model): ... class User_feature1(models.Model): user = models.ForeignKey(User) ... class User_feature2(models.Model): user = models.ForeignKey(User) ... ... class User_feature30(models.Model): user = models.ForeignKey(User) ... If you have 30 tables with foreign key to User table, it will be hard to write 30 select_related queries as User is not the model that holds the foreign key. Even writing raw SQL query is hard with so many models. What is the cleanest method to use? And what is the most performant method? Taking in consideration of calling them from template. Thanks -
How to resolve sql query that is not working in djongo set up
I am using djongo as Sql to Mongodb query convertor in my Django project. However i am facing issues in Server because of Sql queries. Below is the Sql error i am facing while trying to retrieve data in front end UI. raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "engine_task"."id" AS Col1, "engine_task"."project_id" AS Col2, "engine_task"."name" AS Col3, "engine_task"."mode" AS Col4, "engine_task"."owner_id" AS Col5, "engine_task"."assignee_id" AS Col6, "engine_task"."bug_tracker" AS Col7, "engine_task"."created_date" AS Col8, "engine_task"."updated_date" AS Col9, "engine_task"."overlap" AS Col10, "engine_task"."segment_size" AS Col11, "engine_task"."status" AS Col12, "engine_task"."data_id" AS Col13, "engine_task"."dimension" AS Col14, "engine_task"."subset" AS Col15 FROM "engine_task" LEFT OUTER JOIN "engine_segment" ON ("engine_task"."id" = "engine_segment"."task_id") LEFT OUTER JOIN "engine_job" ON ("engine_segment"."id" = "engine_job"."segment_id") WHERE ("engine_task"."owner_id" = %(0)s OR "engine_task"."assignee_id" = %(1)s OR "engine_job"."assignee_id" = %(2)s OR "engine_job"."reviewer_id" = %(3)s OR "engine_task"."assignee_id" IS NULL)) subquery Params: (6, 6, 6, 6) Version: 1.3.4 Below are the versions i am using Django = 3.0.5 mongodb Server = 4.4.6 djongo = 1.3.4 sql parse = 0.2.4 Please help me resolve this issue. -
Django When(...) object SQL missing when used with __in lookup with empty list as value, leading to ProgrammingError
using Django 3.0 (will be upgraded) I get some invalid SQL that leads to a django.db.utils.ProgrammingError, and I wonder if anyone can help me see why. I wonder if this problem also occurs in newer versions of Django. But I hope to get it working without having to upgrade Django right away. Querying a Model I am annotating a field to each instance, and using Case and When with that, and it seems that the error happens when using a negated Q object with a __in lookup that gets an empty list as value. I will show three examples that are very similar, but lead to different SQL. Only the first example leads to erroneous SQL. Example query that leads to invalid SQL: Activity.objects.all() .annotate( employee_authorized=Case( When(~Q(case__assigned_unit__in=[]), then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) This leads to the following SQL, where there's nothing in between WHEN and THEN. This results in a django.db.utils.ProgrammingError. SELECT "activity_activity"."id", ... CASE WHEN THEN False ELSE True END AS "employee_authorized" FROM "activity_activity" LEFT OUTER JOIN "case_case" ON ("activity_activity"."case_id" = "case_case"."id") The below example seems to lead to logical SQL. The only difference being that the Q object is not negated. Activity.objects.all() .annotate( employee_authorized=Case( When(Q(case__assigned_unit__in=[]), then=Value(False)), default=Value(True), output_field=BooleanField(), … -
How to access a table which is present in mysql database in django?
I'm a django beginner and now I got stuck with one issue which is - I'm trying to access a table which is already present in mysql database now I want to render that table on a html page, How can I access that table and render it on html page -
Creating a staff user and giving permissions in Django
I have created a staff user from admin panel for a Django application, but haven't assigned any permissions manually to that user, when I logged in with this staff user credentials I am getting all the permissions by default. I am using custom user but not customised any permissions. please help me with where I am going wrong and how to create a staff user without any permissions by default. -
Django / Blender / Celery / Channels
I found this repository / youtube video https://www.youtube.com/watch?v=42nvLjOv8Ng https://github.com/hophead-ninja/django_blender But Channels has changed quite a bit and I admit I have never tried anything like this with Django before. I have tried to recreate it up using Channels 3.0 - I can get the Webpage up and the Render button "click" does return a 200 from the server - nothing is failing - but the monkey.blend does not render. I do not see my Worker pick up the click I simply get a 200 back from the server Here is my code - maybe together we can make this work. My code is also open source and will be available if we do get it working Here is all of the files and code - if you need anything else please let me know. I do appreciate your help and would love to get the monkey.blend open in a web browser! Thanks for your time. Screenshot of the rendered HTML page /viewer/ html page Which I get a 200 status back and the REDIS IP HTTP GET /viewer/? 200 [0.00, 172.18.0.1:39096] merlin/settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://redis:6379')] }, }, } BLENDER_FILE = ("monkey.blend") … -
Directly send money from my Stripe account to my customers bank accounts
I'm looking for functionality to make direct payments to my Stripe Customers bank accounts without Stripe Connect. Is it actually possible to do? Do I have to use any other payment providers for that? I spent a lot of hours to find correct way of doing such kind of payment flow, but all of them requires Stripe Connect for customer which is unacceptable in my situation. -
ValueError at / time data '' does not match format '%Y-%m-%d'
I'm working on a project in which when users mention a specific date range from and to, the corresponding data gets printed. The page takes input from users through input type date when the specific date is mentioned the value of date passes to user_input_date_to and user_input_date_to. But when I'm executing I'm getting the error ValueError at / time data '' does not match format '%Y-%m-%d' My views file def indexview(request): url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json') json_data=url.json() user_input_state='' user_input_date_from='' user_input_date_to='' user_data_type='' user_required_type='' if request.method == 'POST': user_input_state=request.POST.get('state') x=request.POST['date_from'] user_input_date_to=request.POST['date_to'] user_data_type=request.POST.get('data_period') user_required_type=request.POST.get('required_type') #To store dates list start_date =user_input_date_from end_date = user_input_date_to start_date_object = dt.datetime.strptime(start_date,"%Y-%m-%d").date() end_date_object = dt.datetime.strptime(end_date,"%Y-%m-%d").date() days = end_date_object - start_date_object dates=[] otp=[] for i in range(days.days+1): dates.append(str(start_date_object+dt.timedelta(days=i))) for i in dates: try: otp.append(json_data[user_input_state]['dates'][i][user_data_type][user_required_type]) except KeyError: otp.append(0) dict_pass={ 'dates':dates, 'otp':otp } return render(request,'index.html',dict_pass) HTML date form <input type="date" name="date_from"><br> <input type="date" name="date_to"> -
Manually attach Django UUIDField
So, maybe dumb question but still I'm running into problems. I am using Python + Django (3.1.1) and DRF I have an id field defined as: id = UUIDField(default=uuid.uuid4, unique=True) But I have a use case where someone wants to generate uuid4 on their side and use it in stead of "default" auto-generated one. I am not sure why the UUIDField does not allow manually adding it, and if I can bypass that Thanks! -
How to connect react frontend served on S3 with Django backend hosted on EC2?
I have developed a web application. I am using React.js for the frontend and have used S3 with CloudFront to deploy it on the cloud. For the backend, I have deployed Django REST API on the EC2 container. Everything works fine until I make API call from local server to my API served on EC2. But whenever I change the proxy in the package.json file to my REST API's IP and deploy it on the S3 by invalidating old files. It still doesn't work. How can I resolve this? Any help would be appreciated. -
Large file upload(like 2gb) in chunk by chunk using javascript ajax and django without any api call
My views.py file like this Now I have some problem to stich all the chunks into the file in views.py and also take so much time to upload this video file.Please help. -
Get n items in django model using releverse relationship
Is possible to get the last n items in the Django model, using the reverse relationship. {% for brand in brands %} {% for product in brand.product_set.all %} {% endfor %} {% endfor %} I am tried in this way, But it prints all things. But want only last 3 items