A detailed example of user Registration feature development (python)

Source: Internet
Author: User
Tags button type
A Web application based on the flask fifth, this article mainly introduces the user registration function development, with a certain reference value, interested in small partners can refer to

The following roles are divided into two categories, ordinary users and administrators, at least for ordinary users, the direct modification of the DB is not advisable, to have the user registration function, the following began the development of user registration.

User table

First of all to think good user registration needs to provide what information: User name, password, nickname, mailbox, Birthday, gender, self-introduction, follow these information to modify the user model:

Class User (db. Model): __tablename__= "Users" id=db. Column (db. Integer,primary_key=true) username=db. Column (db. String (#), unique=true,index=true) password=db. Column (db. String (NICKNAME=DB). Column (db. String (EMAIL=DB). Column (db. String (BIRTHDAY=DB). Column (db. DateTime) gender=db. Column (db. Integer) remark=db. Column (db. String (ROLE_ID=DB)). Column (db. Integer,db. ForeignKey ("Roles.id"))

Then use the script to modify the DB

Python default.py db migrate-m "Modify user table"

After carriage return the content of the interface displays:

Then make changes to the DB difference

Python default.py DB Upgrade

Now look at the table structure in DB:

has been modified successfully

Registration interface

Then create a new register.html template and set up the login form:

{% extends "base.html"%} {% block content%} <!--specific content--><p class= "container" > <p class= "Row" ></p> <p class= "Row" > & lt;p> <p class= "Page-header" > 

The register route is then added to the default.py file with the following code:

@app. Route ("/register", methods=["GET"] def Register (): Return Render_template ("/register.html")

Run the interface normally, and then increase the post route:

@app. Route ("/register", methods=["Post"] def registerpost (): User=user (); User.username=request.form.get ("username", "") User.password = Request.form.get ("Password", "") User.birthday = Request.form.get ("Birthday", "") User.email = request.form.get ("email", "") User.gender = Request.form.get ("Gender", "" ) User.nickname = Request.form.get ("nickname", "") user.role_id = 1 #暂时约定公开用户角色为1 #判断, where username, password, nickname cannot be empty if (Len ( User.username.strip ()) ==0):  Flash ("User name cannot be empty")  return Render_template ("/register.html") if (Len ( User.password.strip ()) ==0):  Flash ("User password cannot be empty")  return Render_template ("/register.html") if (Len ( User.nickname.strip ()) = = 0):  Flash ("User nickname cannot be empty")  return Render_template ("/register.html") Db.session.add ( user); Flash ("You have registered successfully") Return Render_template ("/register.html")

The code is a bit verbose, not beautiful, but the basic intention to express clearly, the function can also be achieved, but now the problem comes, add me to add a field, then need to modify three code (Html,form.get, checksum), and in particular the need to modify the HTML, and the HTML part is not verified, If you add client-side validation, you will need to modify more. So is there a tool for optimizing the form, and the answer is, of course, it's WTF's turn.

Introducing WTF Form Frames

As before, you need to install the plugin first.

pip3.6 Install FLASK-WTF

Then introduce the required package

From FLASK.EXT.WTF import formfrom wtforms import Stringfield,passwordfield,submitfield,radiofieldfrom Wtforms.validators Import Datarequired,equalto,length

The following creates a form Registerform:

Class Registerform (Form): username = Stringfield ("Enter user name", validators=[datarequired ()]) password = Passwordfield (" Please enter the password ", validators=[datarequired ()]) Repassword=passwordfield (" Confirm Password ", Validators=[equalto (" password ")]) nickname= Stringfield ("nickname") birthday= Datefield ("date of birth") email= Stringfield ("email address", Validators=[email ()]) gender= Radiofield ("Gender ", choices=[(" 0 "," Male "), (" 1 "," female ")], default=0) remark= Textareafield (" Self Profile ") Submit=submitfield (" Submit ")

To modify the register.html template:

{% extends "base.html"%} {% block content%} <!--specific content-->{% import "bootstrap/wtf.html" as wtf%} <!--import bootstrap template--><p class= "cont Ainer "> <p class=" Row "></p> <p class=" Row ">  <p>   <p class=" Page-header ">    

Execute, output result:

Ah-OU, error, see what the output is wrong:

Pay attention to the red line, is CSRF error, CSRF concept can be directly Baidu, know the problem, in fact, is also very good to modify, in the framework to add a secret key can effectively prevent, in the default.py add a line:

app.config[' secret_key ' = "Niu_blog String"

Key strings can be customized

Then run again and the interface appears:

and contains validation bootstrap validation style, then continue to retrofit default.py has completed this registration function

@app. Route ("/register", methods=["GET", "POST"]) def Register (): Form=registerform () if Form.validate_on_submit ():  user=user ()  user.username=form.username.data  user.password=form.password.data  user.birthday= Form.birthday.data  user.email=form.email.data  user.gender=form.gender.data  user.nickname= Form.nickname.data  user.role_id=1   #暂时约定公开用户角色为1  db.session.add (user) return Render_template ("/ Register.html ", Form=form)

Note The Registerpost method is removed at this time

Well run the test for a bit

Click Submit:

What's wrong with the date format, Theo? This should be read from the source:

Class Datefield (Datetimefield): "" "Same as Datetimefield, except stores a ' datetime.date '." "Def __init__ (self, label=n One, Validators=none, format= '%y-%m-%d ', **kwargs):  super (Datefield, self). __init__ (label, validators, format, * * Kwargs) def process_formdata (self, valuelist):  if valuelist:   date_str = ". Join (ValueList)   try:    Self.data = Datetime.datetime.strptime (Date_str, Self.format). Date ()   except valueerror:    self.data = None    Raise ValueError (Self.gettext (' not a valid date value '))

This is the source of Wtforms field, located in/wtforms/fields/ core.py 745 lines, you can see, the date format supported here is the year-month-day format, the format of the comparison is dead, and the text box is not used HTML5 date but the ordinary text, the solution to say later, temporarily modify the input, change to 1988-2-5, and then click Submit:


Note that since the code commits successfully after it is still returning to this page and injecting the content, there is no problem showing the DB:

Logging into DB Normally, the function is accomplished.

Improve landing page

To change the login page below, first create the login form:

Class LoginForm (Form): Username=stringfield ("Please enter user name", validators=[datarequired ()]) Password=passwordfield ("Please enter password") Submit=submitfield ("Login")

To modify the login Template page:

{% extends "base.html"%} {% import "bootstrap/wtf.html" as WTF%} {% block content%} <!--specific content--><p class= "container" > <p class= "Row" ></p> <p class= "Row" >< C0/><p class= "col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3" >   <p class= "Page-header" >    < H1> welcome you to login 

To modify the routing method:

@app. Route ("/login", methods=["GET", "POST"]) def login (): Form=loginform () if Form.validate_on_submit ():  Username = form.username.data  password = form.password.data  user = User.query.filter_by (username=username, Password=password). First ()  if user is not None:   session["user"] = Username   return render_template ("/ Index.html ", Name=username, Site_name= ' MyBlog ')  else:   Flash (" The user name or password you entered is wrong ")   return Render_template ("/ Login.html ", Form=form) # returns the login page return render_template ("/login.html ", Form=form)

Restart the service, run the program, enter Zhangji and 123 after the successful login home

Back to Home

Now the home of a vast expanse of white, what content is not, the normal light blog should be logged in after the display button, have been concerned about the article, etc., but first to record the status of the login, these will be explained in the next chapter.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.