Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

415
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda