Template form post csrf_token

Using csrf_token in django form post:

<form class="d-grid gap-2" method="post" action="{{ action }}" enctype="multipart/form-data">
			{{ csrf_token }}
			<div class="row">
				<label for="code" class="col-md-2 col-form-label">Code</label>
				<div class="col-md-10">
				  <input type="text" class="form-control" name="code" value="{{ obj.code }}">
				</div>
			</div>
			<div class="row">
				<label for="name" class="col-md-2 col-form-label">Name</label>
				<div class="col-md-10">
				  <input type="text" class="form-control" name="name" value="{{ obj.name }}" required>
				</div>
			</div>
			
			<div class="row">
				<label for="" class="col-md2 col-form-label"></label>
				<div class="col-md-10">
				  <input type="submit" class="btn btn-success" value="Save">
				</div>
			</div>
		</form>

How do we do form post in sanic jinja2 template, without using sanic-wtf?

@app.route("/department/add", name='department-add', methods=['GET', 'POST'])
@app.ext.template("department_form.html")
async def department_add(request):
    if request.method == "GET":
        obj = None
	action = "/department/add"
    	return {"obj": obj, "action": action}
    elif request.method == "POST":
        code = request.form.get('code')
        name = request.form.get('name')
        await Department.create(code=code, name=name)
        return response.redirect("/department/list")


<form class="d-grid gap-2" method="post" action="{{ action }}" enctype="multipart/form-data">
			<!-- ????? -->
			<div class="row">
				<label for="code" class="col-md-2 col-form-label">Code</label>
				<div class="col-md-10">
				  <input type="text" class="form-control" name="code" value="{{ obj.code }}">
				</div>
			</div>
			<div class="row">
				<label for="name" class="col-md-2 col-form-label">Name</label>
				<div class="col-md-10">
				  <input type="text" class="form-control" name="name" value="{{ obj.name }}" required>
				</div>
			</div>
			
			<div class="row">
				<label for="" class="col-md2 col-form-label"></label>
				<div class="col-md-10">
				  <input type="submit" class="btn btn-success" value="Save">
				</div>
			</div>
		</form>

Is this code enough?

app.config.update({
    'SANIC_CSRF_ENABLED': True,
    'SESSION_COOKIE_SECURE': True,
    'SESSION_COOKIE_HTTPONLY': True,
    'SESSION_COOKIE_SAMESITE': 'Lax',
})

Sanic doesn’t come with opinionated OOTB solutions like Django. There is an extension for using jinja. See docs.

Also, you can see sample code from my book on how to implement. Python-Web-Development-with-Sanic/Chapter07/csrf at main · PacktPublishing/Python-Web-Development-with-Sanic · GitHub

That example is for a PWA, but shouldn’t be hard to adapt to paste the code as a form value instead of a cookie.

1 Like