lundi 25 janvier 2016

Django: How can I store in database a variable which I generate in a random function?

My web application is in django and it displays random images every time the user press the 'next' button. I try to store the name or better the number of the image which is concatenated on its name. For example, if the name is 'image4.jpg' then I want to store the number 4 as number or as text.

So, first I have a class in the models.py file.

class Session(User):
    image_number = models.IntegerField()

The type of the variable is probably wrong because I don't want to get this from a form. I generate the number in the views.py file. So, I just want to store it.

As I said I have a function in the views.py file which generates the random numbers.

def func_random(self):
    random_im_list = random.sample(xrange(1,20),5)
    return {1v: random_im_list[0],
            2v: random_im_list[1],
            ... etc}

So, here I generate a list of 5 numbers, because I want to display 5 images in every session. The user presses 5 times the 'next' button and each time he can see a new random image.

I have also in views.py five classes for the five Pages.

class Image1(Page):

class Image2(Page):

class Image3(Page):

class Image4(Page):

class Image5(Page):

Here I need some help because I don't wait any input from the user. I already have generated the list with the random numbers. So, how can I store them on the database? The database after the first session must have 5 columns with one number in each column.

And after that I have the template file:

{% if Page == 1 %}

    <div>
         <im src="{{static_url}}images/image{{ 1v }}.jpg" />   
    <div>
{% elif Page == 2 %}
    <div>
         <im src="{{static_url}}images/image{{ 2v }}.jpg" />   
    <div>

etc....




Aucun commentaire:

Enregistrer un commentaire