Fixing the CSS 404 error caused by using variables in Flask routes: A step-by-step guide

I have created a basic web application to showcase book reviews. Upon a successful search, users are provided with links to book titles - when a link is clicked, the goal is to pass the ISBN of the selected book to the url_for method and then present the corresponding template.

However, when I run my Flask server, the output shows that no CSS is being rendered along with the following information:

"GET /book_data/0316769177 HTTP/1.1" 200 -
"GET /book_data/static/style/style.css HTTP/1.1" 404

In my 'search_results.html' file:

{% for book, isbn in book_dict.items() %}
    <li>
        <a id="book_link" href="{{ url_for('book_data', isbn=isbn) }}">{{ book }}</a>
    </li>
{% endfor %}

In my 'application.py' file:

@app.route("/book_data/<isbn>", methods=["GET"])
def book_data(isbn):

    valid_login = True

    results = db.execute('SELECT * FROM books WHERE isbn = :isbn',
                         {'isbn': isbn}).fetchall()

    book_info = results[0]

    return render_template("book_data.html",
                           valid_login=valid_login,
                           book_info=book_info)

In my 'book_data.html' file:

{% extends "layout.html" %}

{% block login %}

    <div>
        <a class="login_link" href="{{ url_for('signup') }}">Sign Up</a>
        {% if valid_login == True %}
            <a class="login_link" href="{{ url_for('logout') }}">Logout</a>
        {% endif %}
    </div>

{% endblock %}

{% block body %}

    <h> The CSS is not rendering properly on this page</h>

{% endblock %}

All the expected CSS styles are included in 'layout.html' and all other pages are displaying them correctly except this one.

When a link from 'search_results.html' is clicked, the URL displayed is as follows: 127.0.0.1:5000/book_data/0316769177

Answer №1

The server is fetching the style.css file from /book_data/static/style/style.css instead of /static/style/style.css.

To fix this issue, in layout.html, you can try replacing:

<link rel="stylesheet" href="static/style/style.css">

With

<link rel="stylesheet" href="/static/style/style.css">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Immutable value of a fixed attribute and the format of the element's date

I have a couple of inquiries regarding the internet TV site I am currently working on. First, I want the main subscription element to have an attribute called (ServerIP) with a fixed value that cannot be changed. However, the code I tried did not work as e ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

Challenges of Python Web Scraping: Insufficient Extraction of HTML Code

As someone new to Python, I am currently experiencing difficulties with my web scraping code. The script is able to access the website and bypass cookies successfully. However, it is failing to capture the entire HTML code. Here is a snippet of the HTML c ...

Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between tw ...

Exploring the world of AngularJS and delving into the

Lately, I've come across articles discussing Google's ability to now crawl websites and render CSS and Javascript. For example, Google themselves have talked about it in this article: My setup involves a single page application built with Angula ...

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

Is it possible to customize the font color of a placeholder in a v-text-field component in Vue?

Recently, I added the following code snippet to my project: <v-text-field hide-details class="search-field" id="name-input" placeholder="Search by name" v-model="search"></v-text-field> I wanted to change the font color of the placeholder tex ...

Is there a way to view the full HTML source code of this page by selecting the "more" button?

Exploring a web page related to forex trading can be an interesting experience. The website provides a list of live trade records, which can be accessed here: Typically, I use Python along with BeautifulSoup to extract information by reading the source co ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

experiencing a problem when trying to retrieve data from form radio buttons

I've encountered an issue with receiving form data in PHP when dealing with radio buttons created using jQuery. While all input data is received correctly for multiple fields, only the response from the first field's radio button is accurate. For ...

Combining text output using JavaScript, HTML, and Vue

Can you help solve this challenge of outputting concatenated text from a javascript code? The script in question draws a quarter circle that is proportional to the size of the bar and showcases the value of pi accurate to three decimal places. To display ...

Developed a basic HTML form using PHP, however encountering issue where email is not being posted and instead opening a blank page

After creating HTML and PHP documents, I encountered an issue where upon submitting the form, I ended up with a blank page and didn't receive the expected email containing the form information. As someone relatively new to this, I would greatly apprec ...

What is the latest CSS browser support for the min() and max() functions in 2018?

I am considering implementing the use of the min() and max() functions in my project. I'm curious about the current browser support as of 2018. Do you think it is necessary to include the @supports at-rule? For example, I could write: .px-4-safe { ...

Having trouble understanding why the other parts of my header are not displaying

<head> This special function runs when the webpage is loaded. <body onload="myOnload()"> A distinctive div at the top with a unique graphic <div id="header"> <img src="resumeheader.png" alt="Header" style="width:750px;h ...

What is the best way to condense JSON on the back end and then expand it on the front end?

Is there a best practice for compressing large JSON objects being sent between the back-end server (using Flask) and the front-end (Vue JS)? The file size is approximately 35MB, and I'm looking for a way to optimize data transfer in terms of compressi ...

Tips for incorporating a background color into a specific section

Code: .headline { font: 150 50px/0.8 'Pacifico', Helvetica, sans-serif; color: #2b2b2b; text-shadow: 3px 3px 0px rgba(0, 0, 0, 0.1), 7px 7px 0px rgba(0, 0, 0, 0.05); text-align: center; } <link href='http://fonts.googleapis.com ...

Box size adjusts to fit its content, including any form fields

Looking to create a box that adjusts its size based on content and center it without resorting to using tables for layout or setting fixed sizes. How can this be achieved while keeping the markup clean? I've almost got it, but the form fields are not ...

Transforming a Java Array or Collection into a JSON array

After running my Java code, the returned Collection (ArrayList) produces JSON through JAXB that looks like: {"todo":[{"name":"CAMPBELL","sales":"3","time":"1331662363931"}, {"name":"FRESNO","sales":"2","time":"1331662363931"}]} However, I am wondering if ...

Is it possible to choose tags from a different webpage?

Imagine you have a page named a.html which contains all the jQuery code, and another page called b.html that only includes HTML tags. Is it feasible to achieve something like this: alert( $('a').fromhref('b.html').html() ); In essence ...

Align text vertically within labels and links styled with bootstrap

When using bootstrap button styled labels and links with a larger height than default, the text tends to be vertically aligned at the upper side of the button. However, when using an actual button element, the text is centered vertically. Is there a way t ...