Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

1
Django : passing model instance from template to view
Post Body

(It is my first time posting, sorry if I'm doing mistakes)

Hello, I am following the Django tutorial for my first app and I'm trying to make an app that display 5 random gifs (from Reddit Rest API and subreddit /r/gifs). Then I would like to be able to choose one of them and add them to my database.

I have a solution that works like that :

models.py :

class Favorite_GIF(models.Model):
    ## URL gfycat
    url = models.CharField(max_length=200)
    ## Preference score
    score = models.IntegerField(default=0)
    def __str__(self):
        return self.url

I am passing a list of Favorite_GIF instances from my views.py to my template with the help of the context. I had to make a list of Favorite_GIF instances in order to capture all the information about the gifs because they are not saved in the database yet.

random_GIF.html :

<p>Here are displayed 5 random GIF</p>

{% if random_GIF_list %}
    <ul>
    <form action="{% url 'app_1:add_favorite_GIF' %}" method="post">
    {% csrf_token %}
    {% for random_GIF in random_GIF_list %}
        <img src={{ random_GIF.url }} align="left"> 
        <input type="radio" name="random_GIF_URL" id="random_GIF_URL{{ forloop.counter }}" value={{ random_GIF.url }}/>
        <input type="hidden" name="random_GIF_Score" value="{{ random_GIF.score }}">
        <input type="submit" value="Add to favorites" />
        <br clear="all" />
    {% endfor %}
</form>
    </ul>
{% else %}
    <p>No random GIF are available.</p>
{% endif %}

My problem here is that I am unable to post the instance of {{ random_GIF }} (which is the same as {{ random_GIF .url
}} because of the

def __str__(self):
    return self.url

?)

An so I had to deconstruct my instances to pass each variable and then reconstruct my instances in my add_favorite_GIF view, which I feel is very bad coding.

Do you have any suggestions to my problem ? Thank you

Author
Account Strength
80%
Account Age
7 years
Verified Email
Yes
Verified Flair
No
Total Karma
n/a
Link Karma
5
Comment Karma
n/a
Profile updated: 6 days ago
Posts updated: 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
7 years ago