Search code examples
pythonflasktweepy

is there a way to remove UndefinedError in this code?


I am trying to display results of the most trending topics from twitter to my webpage but when i run the application it return jinja2.exceptions.UndefinedError: 'trends' is undefined. I suspect that i am not using try/except how its supposed to.

@app.route('/')
def index():
    try:
        location = request.args.get('location')
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        return render_template('index.html',trends=trends)
    except tweepy.error.TweepError:
        return render_template('index.html')

I also think there is an issue in my template code.

<div class="column">
        <form  method="GET" action="{{url_for('index')}}">
            <div class="form-group">
                <p>See whats tending in your area.</p>
                <label for="">Enter location name</label>
                <input type="text" name="location" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">
            </div>
        </form>
    </div>

    <div class="column">
        <h4>Top Trending</h4>
        <ul class="list-group">
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
          </ul>
    </div>

Solution

  • Better to reorganize things something like this, to not query things if there is no location entered, and to not try to access trends if it's not set:

    @app.route("/")
    def index():
        location = request.args.get("location")
        trends = None
        if location:  # Only query if there is a location
            loc_id = client.fetch_woeid(str(location))
            trends = api.trends_place(int(loc_id))
            # the above will throw an error if the place is invalid, that's fine
        return render_template("index.html", trends=trends, location=location)
    

    and

    <div class="column">
        <form method="GET">
            <div class="form-group">
                <p>See whats trending in your area.</p>
                <label for="">Enter location name</label>
                <input type="text" name="location" value="{{ location|default("") }}" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">
            </div>
        </form>
    </div>
    
    
    <div class="column">
        {% if trends %}
        <h4>Top Trending</h4>
        <ul class="list-group">
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
          </ul>
        {% endif %}
    </div>