[Answer]-Random queryset from a txt file in Django

1👍

There are two parts to this question, so let’s break it up.

Getting a random line from a file is easy, and isn’t related to django:

import random

def random_line_from_file(f):
    """Return a random line from an open file-like object"""
    return random.choice(f.readlines())

with open('myfile.txt') as f:
    print random_line_from_file(f)

Now you use that code wherever you want to show a random URL, for example:

def sample_view(request):
    with open('myfile.txt') as f:
        url = random_line_from_file(f)

    return render(request, 'sometemplate.html', {'random_url': url})

I’m not sure if you need a generic view, if you have multiple different views, it might be easier to just put in a call to your simple python function, and put the random URL in the template context. YMMV


If you don’t want to clutter your view code with this, you could also write a custom template tag that returns a random URL.

@register.assignment_tag
def get_random_url():
    with open('myfile.txt') as f:
        url = random_line_from_file(f)
    return url

Use it in your templates like this:

{% get_random_url as my_url %}
<p>Look at this: {{ my_url }}.</p>

You may then store the result in a template variable using the as argument followed by the variable name, and output it yourself where you see fit:

{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}

See https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags for more information on custom template tags.

0👍

Write a simple method and use it in all needed views.
Simple example:

from random import randint

def get_random_url():
    with open('links.txt', 'r') as f:
        links = f.split('\n')
        return links[randint(0, len(links))]

Also you can move filename to django settings file.

Leave a comment