Search code examples
pythondjangoreddit

URL patterns and how to use them for external link django


Inexperienced with Django, but I have been playing with the Reddit API and it is easy and fun to use. I think I don't understanding something fundamental about template tags and urls in Django. All I really want to do is to have an href link to 'http://redd.it/' with the reddit id for the post after the slash.

My model is:

class Reddit_Model(models.Model):
    reddit_title = models.CharField(max_length=500,default='')
    reddit_score = models.CharField(max_length=20,default='')
    reddit_id = models.CharField(max_length=20,default='')
    reddit_url=models.URLField(blank=True,max_length=500)

And in the template if I use:

<a href="{{ entry.reddit_url }}">{{ entry.reddit_url }}</a>

I connect to the external URL as expected.

However that URL can be the external URL that someone put in their post, so if I want to go back to the persons post (for example a post that has a reddit_id of ge2oap) and I type into the browser http://redd.it/ge20ap it will go to the post as desired. However when I try to construct a template tag I run into problems. if I use

<a href="{{http://redd.it/{{entry.reddit_id}}}">http://redd.it/{{ entry.reddit_id }}</a>

and got

http://127.0.0.1:8000/mainapp/'http://redd.it'%20ge2oap

which I think makes sense, so I tried various URL template tag patterns

<a href="{% url 'http://redd.it/' entry.reddit_id %}">http://redd.it/{{ entry.reddit_id }}</a>

none of which work. I suppose I could create another field in the model. I looked at the redirect functions and the get_absolute_URL() in the docs, but didn't see how they could be used in this situation, so I suspect I am missing something obvious. Any suggestions?


Solution

  • <a href="{{http://redd.it/{{entry.reddit_id}}}">http://redd.it/{{ entry.reddit_id }}</a>
    

    should be

    <a href="http://redd.it/{{entry.reddit_id}}">http://redd.it/{{ entry.reddit_id }}</a>
    

    as the first part of the href isn't a template variable. Note that you can't nest braces like that anyway.