Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

413
Views
eliminate duplicates in django

I'm trying to pick up 3 random numbers out of a list of 20 numbers.

In views.py, I've defined this variable:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

In my template index.html:

{{ nums|random }} - {{ nums|random }} - {{ nums|random }}

I want to get 3 different numbers, but I don't know which filter/tag to apply.

I've tried if/else statements, for loops, (if there's a duplicate I want a redraw) but i'm not satisfied with the results and I'm pretty sure there's a simple filter to do that.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I don't think there's a reasonable way to do this with the built in filters. I'd just pick the numbers in the view and pass that in to the context.

If your rendering is consistent and you want to do this a lot of places you could write a custom template tag, eg:

import random
from django import template

register = template.Library()

@register.simple_tag
def random_sample(population, k):
    return ' - '.join(str(choice) for choice in random.sample(population, k))

Then {% random_sample nums 3 %} in your template.

But I think doing it in the view is simpler.

over 4 years ago · Santiago Trujillo Report

0

You could create your templatetag with this functionalitiy to solve your problem.

yourapp/templatetags/custom_choice_tags.py

from django import template
import random

register = template.Library()

@register.assignment_tag
def get_three_unique_random_values_from_list(value_list):
    random_choices = random.sample(value_list, 3)
    selected_choices = {
        'first_choice': random_choices[0],
        'second_choice': random_choices[1],
        'third_choice': random_choices[2],
    }
    return selected_choices

and then in your template.html:

{% load custom_choice_tags %}

{% get_three_unique_random_values_from_list random_list  as random_choices %}

 {{ random_choices }} 

the variable random_list would be passed from your view into the template context in this example.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!