Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The error I'm getting-

werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'home'. Did you mean 'main.home' instead?


Code for my routes.py folder-

Python
from flask import render_template, request, Blueprint
from flaskblog.models import Post

main = Blueprint('main', __name__)


@main.route("/")
@main.route("/home")
def home():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
    return render_template('home.html', posts=posts)


@main.route("/about")
def about():
    return render_template('about.html', title='About')


Code for my home.html folder-

HTML
{% extends "layout.html" %}
{% block content %}
    {% for post in posts.items %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="{{ url_for('user_posts', username=post.author.username) }}">{{ post.author.username }}</a>
              <small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d') }}</small>
            </div>
            <h2><a class="article-title" href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
        </article>
    {% endfor %}
    {% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
      {% if page_num %}
        {% if posts.page == page_num %}
          <a class="btn btn-info mb-4" href="{{ url_for('home', page=page_num) }}">{{ page_num }}</a>
        {% else %}
          <a class="btn btn-outline-info mb-4" href="{{ url_for('home', page=page_num) }}">{{ page_num }}</a>
        {% endif %}
      {% else %}
        ...
      {% endif %}
    {% endfor %}
{% endblock content %}


Code for my layout.html folder-

HTML
<!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">

    {% if title %}
        <title>Flask Blog - {{ title }}</title>
    {% else %}
        <title>Flask Blog</title>
    {% endif %}
</head>
<body>
    <header class="site-header">
      <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
        <div class="container">
          <a class="navbar-brand mr-4" href="/">Flask Blog</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
            
          </button>
          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
              <a class="nav-item nav-link" href="{{ url_for('home') }}">Home</a>
              <a class="nav-item nav-link" href="{{ url_for('about') }}">About</a>
            </div>
            <!-- Navbar Right Side -->
            <div class="navbar-nav">
              {% if current_user.is_authenticated %}
                <a class="nav-item nav-link" href="{{ url_for('new_post') }}">New Post</a>
                <a class="nav-item nav-link" href="{{ url_for('account') }}">Account</a>
                <a class="nav-item nav-link" href="{{ url_for('logout') }}">Logout</a>
              {% else %}
                <a class="nav-item nav-link" href="{{ url_for('login') }}">Login</a>
                <a class="nav-item nav-link" href="{{ url_for('register') }}">Register</a>
              {% endif %}
            </div>
          </div>
        </div>
      </nav>
    </header>
    <main role="main" class="container">
      <div class="row">
        <div class="col-md-8">
          {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
              {% for category, message in messages %}
                <div class="alert alert-{{ category }}">
                  {{ message }}
                </div>
              {% endfor %}
            {% endif %}
          {% endwith %}
          {% block content %}{% endblock %}
        </div>
        <div class="col-md-4">
          <div class="content-section">
            <h3>Our Sidebar</h3>
            <p class='text-muted'>You can put any information here you'd like.
              <ul class="list-group">
                <li class="list-group-item list-group-item-light">Latest Posts</li>
                <li class="list-group-item list-group-item-light">Announcements</li>
                <li class="list-group-item list-group-item-light">Calendars</li>
                <li class="list-group-item list-group-item-light">etc</li>
              </ul>
            </p>
          </div>
        </div>
      </div>
    </main>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>


What I have tried:

I have tried few things but none of them were able to fix the problem in any way, at all. Kindly Help.
Posted
Updated 10-Dec-22 13:01pm
v3

It looks like the home function in your routes.py file is defined as part of a Flask blueprint named main. When using a blueprint, you need to prefix the endpoint name with the name of the blueprint when generating URLs using url_for.

In your home.html file, you are generating URLs for the home endpoint without prefixing the name of the blueprint. To fix this error, you can update the url_for calls to use the main.home endpoint instead of just home:

{% extends "layout.html" %}
{% block content %}
    {% for post in posts.items %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="{{ url_for('user_posts', username=post.author.username) }}">{{ post.author.username }}</a>
              <small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d') }}</small>
            </div>
            <h2><a class="article-title" href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
        </article>
    {% endfor %}
    {% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
      {% if page_num %}
        {% if posts.page == page_num %}
          <a class="btn btn-info mb-4" href="{{ url_for('main.home', page=page_num) }}">{{ page_num }}</a>
        {% else %}
          <a class="btn btn-outline-info mb-4" href="{{ url_for('main.home', page=page_num) }}">{{ page_num }}</a>
        {% endif %}
      {% else %}
        ...
      {% endif %}
    {% endfor %}
{% endblock content %}


In the code above, the url_for('main.home') calls have been updated to include the name of the blueprint (main) before the endpoint name (home). This should fix the BuildError that you're seeing.
 
Share this answer
 
Comments
Aalam Pratap Bedi 10-Dec-22 23:57pm    
@MikeBrainy I made the changes as you suggested and replaced 'home' with 'main.home' and about with 'main.about', wherever necessary, inside home.html page and layout.html page and my code did work. Thanks for helping pal.
Try the following change:
Python
return render_template('main/home.html', posts=posts) # add the 'main/' prefix to the template name.

and the same for 'about'.

[edit]
Looking at the structure of my flask application I would suggest that all the files you have put in the 'main' folder should be moved up a level into flaskblog. What I have is as follows:
 Directory of flaskr

07/09/2022  11:59    <DIR>          static
07/09/2022  12:00    <DIR>          templates
19/07/2022  12:05             1,101 __init__.py
19/07/2022  11:48             2,553 auth.py
19/07/2022  12:22             2,644 blog.py
19/07/2022  11:17               888 db.py
19/07/2022  11:14               435 schema.sql

 Directory of flaskr\static

19/07/2022  12:01             1,828 style.css

 Directory of flaskr\templates

07/09/2022  12:01    <DIR>          auth
07/09/2022  12:00    <DIR>          blog
19/07/2022  11:48               739 base.html

 Directory of flaskr\templates\auth

19/07/2022  11:55               439 login.html
19/07/2022  11:51               443 register.html

 Directory of flaskr\templates\blog

19/07/2022  12:10               462 create.html
19/07/2022  12:07               818 index.html
19/07/2022  12:14               716 update.html

Although the names will be different that structure seems to be the standard one that flask works to.

[/edit]
 
Share this answer
 
v2
Comments
Aalam Pratap Bedi 10-Dec-22 9:24am    
@Richard MacCutchan I made the changes as you suggested, but my code did'nt work. After applying changes, as suggested by you, i get the following error- "jinja2.exceptions.TemplateNotFound: main/home.html".
Richard MacCutchan 10-Dec-22 9:56am    
Where are your templates? They should be in a folder named 'main' under the 'templates' folder. Flask has a very specific structure and naming system which you must adhere to.
Aalam Pratap Bedi 11-Dec-22 1:39am    
I have separate folder for 'template' and 'main', which are both under the flaskblog folder. Inside my template folder are all the html pages. And inside my main folder I have __init__.py and routes.py pages.
Richard MacCutchan 11-Dec-22 3:12am    
See my updated solution above.
Aalam Pratap Bedi 11-Dec-22 3:34am    
Thanks for helping buddy. I have been able to solve the issue with a different method. Your method also seems to solve the issue and, so out of curiosity, I'll give your method a try as well.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900