Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Getting single post

How can we get a single post when clicked on view? I tried doing something along the line of getting post.id however I get an error. Can someone help me or guide me on how to access single posts?

in the template file stream.html the link is as follows:

<a href="{{ url_for('singlepost', post=post.id) }}"> 
            {{ post.content}} 
                    </a> 

While in the app.py view function is as follows:

@app.route('/post')
@app.route('/post/<int:postid>')
def singlepost(postid=None):
    post = models.Post.select().where(models.Post.id == postid).get()
    return render_template("singlepost.html", post=post)

[MOD: fix codeblock formatting -cf]

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

The issue appears to be a disagreement between your url_for arguments and the app.route parameters:

Your route is @app.route('/post/<int:postid>'). parameter name is postid

Your url_for has {{ url_for('singlepost', post=post.id) }}. argument name is post should be postid

Change url_for usage to {{ url_for('singlepost', postid=post.id) }}

It worked thank you!

Is this in reference to Flask? Post the code you're having a problem with here as well!

Yes, it's reference to flask. Just added the code. sorry for the terrible mark down first time poster)

In the html, there's one problem

<a href="{{ url_for('singlepost', post=post.id) }}"> {{ post.content}} </a> 

<a href="{{ url_for('singlepost', post=post.id) }}"> {{ post.content }} </a> 

I added a space at the end of the {{ post.content }} as that would have caused a problem I think;

Next problem, add the get and post methods to the view.

@app.route('/post/<int:postid>') 
def singlepost(postid=None): 
  post = models.Post.select().where(models.Post.id == post_id) # <-- that is a guess, but I think it will fix your problem 
  return render_template("singlepost.html", post=post)

You didn't need the .get() IF you are only displaying posts, if you are trying to make a view for creating posts this doesn't work at all! Otherwise it's fine! Post to this thread again if you need any more help!

Thank you! I managed to do it using the request function. But thank you so much!