question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] How can I create a web form using jinja template?

See original GitHub issue

Hi,

I’m new to FastAPI (and web frameworks in general), so I hope one of you can help me. I’ve read the docs, but I cant figure out how to create a web form with Jinja.

As my first project I would like to create a simple blog using FastAPI and Jinja.

I tried to this:

from fastapi import FastAPI, Form
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
from pydantic import BaseModel


app = FastAPI()

app.mount("/static", StaticFiles(directory="./app/static"), name="static")


templates = Jinja2Templates(directory="./app/templates")

class Username(BaseModel):
    username: str


class Login(BaseModel):
    username: str = Form(..., title="Your username", max_lengthe=20)
    password: str = Form(..., title="Your password")

@app.post("/login/", response_model=Username)
async def login(request: Request, Login):
    pass

Not sure if any of this is the correct way of doing it, but I could not figure out what to put in the login function.

Any help is much appreciated 😃

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
tiangolocommented, Feb 17, 2020

@albertfreist you would probably implement it with something like this:

from fastapi import FastAPI, Form, Cookie, Depends
from starlette.responses import RedirectResponse, Response

app = FastAPI()


def get_current_user(session: str = Cookie(None)):
    if not session:
        return None
    else:
        data = decrypt(session)  # some cryptography decryption
        user = query_user(data["user"])  # Query user
        return user


@app.get("/")
def main(current_user=Depends(get_current_user)):
    if not current_user:
        return "Some generic template or a redirection"
    return "Some user specific template"


@app.post("/login")
def login(
    response: Response,
    username: str = Form(..., min_length=3, max_length=64),
    password: str = Form(..., min_length=8),
    remember_me: bool = Form(False),
):
    user = get_user(username)  # some DB query here
    if not user or not user.check_password(password):
        return RedirectResponse("/login?invalid=True", status_code=302)
    response.set_cookie("session", "someencrypted session token")
    return RedirectResponse("/", status_code=302)


@app.get("/login")
def login(invalid: bool = False, current_user=Depends(get_current_user)):
    if current_user.is_authenticated:
        return RedirectResponse("/")
    return render_template("auth/login.html", title="Sign in", invalid=invalid)

You would probably need to access a database, to implement security to encrypt and decrypt a token or similar, to use dependencies to get a user, to use cookies to set and retrieve a session, etc. All that is in the docs, you can search for each specific subject.

On the other side, have in mind that for modern applications it’s a lot more common to not use rendered templates, and instead, have a frontend framework show the information retrieved from an API. FastAPI is optimized to be used for APIs. If all your workflow is based on templates, FastAPI is more or less comparable to any other framework and you probably won’t notice a big advantage over others in that scenario, especially if you already have some code in place with a different framework. Maybe FastAPI will be a bit faster and other small benefits, but you probably won’t see a huge benefit from it.


On the other side, if your only purpose is to write a blog, I would suggest Dev.to or Medium. If you want to have your own blog and build it, I would suggest you use a JAMStack that builds a static site from code, instead of a full backend with DB and everything. And you could serve it for free on Netlify or other providers. You could use Hugo, Gatsby with markdown, MkDocs or others.

But if your main objective is to learn backend development, I would suggest instead to just follow the FastAPI tutorial, step by step. That would give you some solid foundations to build backends and APIs that can be easily used by other systems and frontend teams.

1reaction
hotheadhackercommented, Aug 10, 2021

@albertfreist after struggling a lot with same problem I’ve found this easy solution. Instead of heavy loading each params we can use {{request.query_params["someParam"]}} or for whole querystring {{request.query_params}}

Read more comments on GitHub >

github_iconTop Results From Across the Web

Learn Flask: Jinja2 Templates and Forms Cheatsheet
Flask provides a simple workflow to implement web forms and gather data while ensuring proper form validation. Using the modules WTForms and Flask-WTF,...
Read more >
How To Use Web Forms in a Flask Application - DigitalOcean
In this tutorial, you'll build a small web application that demonstrates how to use web forms. The application will have a page for...
Read more >
Primer on Jinja Templating - Real Python
With Jinja, you can build rich templates that power the front end of your web applications. But you can use Jinja without a...
Read more >
Rendering Pages in Flask Using Jinja - Hackers and Slackers
Flask's approach to this is via a templating system called Jinja2: and HTML preprocessor which lets us write HTML, which changes based on...
Read more >
How To Use Python On A Web Page With Jinja2 - YouTube
In this video we 'll start to look at the Jinja2 Template Language that allows us to use Python directly on our webpages....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found