0

I've just started learning flask. I'm trying to handle a form for user registration. But inside my routes.py, the form's data isn't getting pushed to the database, and also the page isn't redirecting after the click on the submit button. There is no error or any warning. The action just does not get performed and the register page just gets re-loaded.

I'm attaching the codes of the files below. The demo is the folder where my HTML templates and .py files are saved.

#run.py : located outside the root(demo) folder
from demo import app


if __name__ == '__main__':
    app.run(debug=True)

-------------------------------------------------------------------------------------

#__init__.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///demo.db'
app.config['SECRET_KEY'] = 'df159ba68c3577847ef3dfef'
db = SQLAlchemy(app)

from demo import routes


-------------------------------------------------------------------------------------

#model.py
from demo import db


class Item(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   username = db.Column(db.String(50), nullable=False, unique=True)
   email = db.Column(db.String(100), unique=True)
   password = db.Column(db.String(60), nullable=False)

   def __repr__(self):
       return f'Item {self.username}'


------------------------------------------------------------------------------------

#form.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField


class RegisterForm(FlaskForm):
   username = StringField(label='Username')
   email = StringField(label='Email')
   password = PasswordField(label='Password')
   submit = SubmitField(label='Create Account')


-------------------------------------------------------------------------------------

#routes.py
from demo import app
from flask import render_template, redirect, url_for
from demo.model import Item
from demo.form import RegisterForm
from demo import db


@app.route('/')  
@app.route('/home')
def hello_world():
    return render_template('home.html', item_name="number")


@app.route('/info')
def second_page():
    items = Item.query.all()
    return render_template('info.html', items=items)


@app.route('/register', methods=['GET', 'POST'])
def registration_page():
    form = RegisterForm()
    if form.validate_on_submit():
       user_to_create = Item(username=form.username.data,
                          email=form.email.data,
                          password=form.password.data)
       db.session.add(user_to_create)
       db.session.commit()
       return redirect(url_for('second_page'))
return render_template('register.html', form=form)


-----------------------------------------------------------------------------------


#register.html
{% extends 'base.html' %}

{% block title %}
   Registration page
{% endblock %}

{% block content %}
    <form method="POST" >
      {{ form.username.label() }}
      {{ form.username(placeholder='Enter Your Username') }}

      {{ form.email.label() }}
      {{ form.email(placeholder='Enter Your Email') }}

      {{ form.password.label() }}
      {{ form.password(placeholder='Enter Your Password') }}

      {{ form.submit() }}
   </form>
{% endblock %}


----------------------------------------------------------------------------------


#info.html :The page from second_page() function in routes.py
{% extends 'base.html' %}
{% block title %}
   This is Info page
{% endblock %}

{% block content %}
   <h1>you are in the info page</h1>
   <h1>Welcome to this page</h1>
   <h1>Great day!</h1>
   {% for item in items %}
      <p>{{ item.username }} - {{ item.email }}</p>
   {% endfor %}
{% endblock %}

These are the files from my project. Please help me clear this functionality error. Thanks in advance.

2
  • You might want to follow the tutorial more closely, as there are some differences with how you set up the form itself inside the template, which may be the source of the issues. Commented Jun 22, 2021 at 5:54
  • Sure @metatoaster! Thank you very much! I'll look into it. Can you also please point out where it had gone wrong? Commented Jun 22, 2021 at 5:57

1 Answer 1

1

Your form is never validated because are you have not used csrf token. You can try printing print(form.errors) before and after the if statement

[...]
form = RegisterForm()
print(form.errors)
if form.validate_on_submit():
   user_to_create = Item(username=form.username.data,
                      email=form.email.data,
                      password=form.password.data)
   db.session.add(user_to_create)
   db.session.commit()
   return redirect(url_for('second_page'))
print(form.errors)
return render_template('register.html', form=form)

first it will give no error but after submiting it will give no crsf token

In html You can add {{form.csrf_token}}

 <form method="POST" >
  {{ form.csrf_token }} // add this and this should work
  {{ form.username.label() }}
  {{ form.username(placeholder='Enter Your Username') }}

  {{ form.email.label() }}
  {{ form.email(placeholder='Enter Your Email') }}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much @charchit It worked!! Can I contact you again if I had any doubts as to such? If yes, let me know the medium to contact you. I'd love to get your help as I keep learning flask
welcome, you can conntact me on discord charchit#8198. If you want you can mark this as correct answer.
Sure thank you!! Yes yes I just marked it. Sure I'll contact you on discord.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.