Database Model Implementation We create a table notes, with the columns title, description, author,subject and a publication date. We also mention that the fields title, description,author are required, and that the publication date will be automatically assigned the current time.db.define_table(notes, Field(title, length=200, required=True, requires=IS_NOT_EMPTY()), Field(description, length=2000, required=True, requires=IS_NOT_EMPTY()), Field(author, db.auth_user, required=True, requires=IS_NOT_EMPTY()), Field(subject, length=20,requires=IS_IN_SET((english, philosophy, metaphysics))), Field(pub_date, datetime, default=request.now, writable=False) )
We need functions that handle therequest from user.
Function Definition to handle CRUDoperations. (index)def index(): Makes a db query to select all the notes, orders the notes by the publication date and returns a dictionary to the template, containing all the notes. response.flash = "Welcome to the index view!" notes = db(db.notes).select(orderby=db.notes.pub_date) return dict(notes=notes)
Function Definition contd.. (create)def create(): Generates a form corresponding to the model and renders it, if the form sends some data, the function validates the data and saves the data in the database. response.flash = "This is the create page" form=SQLFORM(db.notes) if form.process().accepted: response.flash = form accepted elif form.errors: response.flash = form has errors else: response.flash = please fill the form return dict(form=form)
Function Definitions contd.. (edit)def edit(): The function pre-populates the data from the note instance that has been requested to be edited and renders it, once client sends in some data, it saves it in the database. note = db.notes(request.args(0)) or redirect(URL(error)) form=SQLFORM(db.notes, note, deletable = True) if form.validate(): if form.deleted: db(db.notes.id==note.id).delete() redirect(URL(index)) else: note.update_record(**dict(form.vars)) response.flash = records changed else: response.flash = Something went wrong! return dict(form=form)
2 basic templates would do the job!The previous slide shows how to create atemplate. We need to create a template toshow all the content (index.html) and atemplate to create/edit the content(create.html)The files can be found here.
Its Done!!Its time to reap the fruits of the hard workweb2py just did for us :)The source code is available here.You can share it if you liked it, in case of doubtssend a mail to: email@example.com.