Creating A Blog Tutorial
This section of the documentation will contain various tutorials. These are guides that are designed to take you from beginning to end on building various types of projects with Masonite. We may not explain things in much detail for each section as this part of the documentation is designed to just get you familiar with the inner workings of Masonite.
Since this section of the documentation is designed to just get you up and coding with Masonite, any further explanations that should be presented are inside various "hint blocks." Once you are done with the tutorial or simply want to learn more about a topic it is advised that you go through each hint block and follow the links to dive deeper into the reference documentation which does significantly more explaining.

Hint Blocks

You will see various hint blocks throughout the tutorials. Below are examples of what the various colors represent.
You'll see hint blocks that are green which you should follow if you want to learn more information about the topic currently being discussed.
You'll also see hint blocks that are blue. These should not be ignored and typically contain background information you need to further understand something.

Installation

This tutorial will assume you have already installed Masonite. If you haven't, be sure to read the Installation guide to get a fresh install of Masonite up and running. Once you have one up and running or if you already have it running, go ahead and continue on.

Creating a Blog

In this tutorial we will walk through how to create a blog. We will touch on all the major systems of Masonite and it should give you the confidence to try the more advanced tutorials or build an application yourself.

Routing

Typically your first starting point for your Masonite development flow will be to create a route. All routes are located in routes/web.py and are extremely simple to understand. They consist of a request method and a route method. Routing is simply stating what incoming URI's should direct to which controllers.
For example, to create a GET request route it will look like:
routes/web.py
1
from masonite.routes import Route
2
3
ROUTES = [
4
Route.get('/url', '[email protected]')
5
]
Copied!
We'll talk more about the controller in a little bit.
You can read more about routes in the Routing documentation

Creating our Route:

We will start off by creating a view and controller to create a blog post.
A controller is a simply a class that inherits from Masonite's Controller class and contains controller methods. These controller methods will be what our routes will call so they will contain most of our application's business logic.
Think of a controller method as a function in the views.py file if you are coming from the Django framework
Let's create our first route now. We can put all routes inside routes/web.py and inside the ROUTES list. You'll see we have a route for the home page. Let's add a route for creating blogs.
routes/web.py
1
ROUTES = [
2
Route.get('/', '[email protected]').name('welcome'),
3
4
# Blog Routes
5
Route.get('/blog', '[email protected]')
6
]
Copied!
You'll notice here we have a [email protected] string. This means "use the blog controller's show method to render this route". The only problem here is that we don't yet have a blog controller.

Creating a Controller

All controllers are located in the app/controllers directory by default and Masonite promotes a 1 controller per file structure. This has proven efficient for larger application development because most developers use text editors with advanced search features such as Sublime, VSCode or Atom. Switching between classes in this instance is simple and promotes faster development. It's easy to remember where the controller exactly is because the name of the file is the controller.
You can of course move controllers around wherever you like them but the craft command line tool will default to putting them in separate files. If this seems weird to you it might be worth a try to see if you like this opinionated layout.

Creating Our First Controller

Like most parts of Masonite, you can scaffold a controller with a craft command:
terminal
1
$ python craft controller Blog
Copied!
This will create a controller in app/controllers directory that looks like this:
app/http/controller/BlogController.py
1
from masonite.controllers import Controller
2
from masonite.views import View
3
4
5
class BlogController(Controller):
6
def show(self, view: View):
7
return view.render("")
Copied!
Simple enough, right? You'll notice we have a show method we were looking for. These are called "controller methods" and are similiar to what Django calls a "view."
But also notice we now have our show method that we specified in our route earlier.

Returning a View

We can return a lot of different things in our controller but for now we can return a view from our controller. A view in Masonite are html files or "templates". They are not Python objects themselves like other Python frameworks. Views are what the users will see (or view).
This is important as this is our first introduction to Masonite's IOC container. We specify in our parameter list that we need a view class and Masonite will inject it for us.
For now on we won't focus on the whole controller but just the sections we are worried about. A ... means there is code in between that we are not worried about:
app/controllers/BlogController.py
1
from masonite.view import View
2
# ...
3
def show(self, view: View):
4
return view.render('blog')
Copied!
Notice here we "type hinted" the View class. This is what Masonite calls "Auto resolving dependency injection". If this doesn't make sense to you right now don't worry. The more you read on the more you will understand.

Creating Our View

You'll notice now that we are returning the blog view but it does not exist yet.
All views are in the templates directory. We can create a new file called templates/blog.html.
We can put some text in this file like:
templates/blog.html
1
This is a blog
Copied!
Let's run the migration for the first time:
terminal
1
$ python craft migrate
Copied!
and then run the server
terminal
1
$ python craft serve
Copied!
and open up http://localhost:8000/blog. You will see "This is a blog" in your web browser.

Authentication

Most applications will require some form of authentication. Masonite comes with a craft command to scaffold out an authentication system for you. This should typically be ran on fresh installations of Masonite since it will create controllers, routes, and views for you.
For our blog, we will need to setup some form of registration so we can get new users to start posting to our blog. We can create an authentication system by running the craft command:
terminal
1
$ python craft auth
Copied!
We should get a success message saying that some new assets were created. You can check your controllers folder and you should see a few new controllers there that should handle registrations.
You can then add the authentication routes to your project:
1
from masonite.authentication import Auth
2
3
ROUTES = [
4
Route.get('/', '[email protected]').name('welcome'),
5
6
# Blog Routes
7
Route.get('/blog', '[email protected]')
8
]
9
10
ROUTES += Auth.routes()
Copied!
We will check what was created for us in a bit.

Database Setup

In order to register these users, we will need a database. By default, Masonite uses SQLite. If you want to use a different database you can change the options that start with DB_ in your .env file. For running MySQL or Postgres you will need to have those databases setup already.
We have already run the migration command before, which was:
terminal
1
$ python craft migrate
Copied!
If you want to use MySQL, open up the .env file in the root of your project and change the DB_DATABASE to mysql. Also, feel free to change the DB_DATABASE name to something else.
.env
1
DB_CONNECTION=mysql
2
DB_HOST=127.0.0.1
3
DB_PORT=3306
4
DB_DATABASE=masonite
5
DB_USERNAME=root
6
DB_PASSWORD=
Copied!

Migrating

Once you have set the correct credentials, we can go ahead and migrate the database. Out of the box, Masonite has a migration for a users table which will be the foundation of our user. You can edit this user migration before migrating but the default configuration will suit most needs just fine and you can always add or remove columns at a later date.
terminal
1
$ python craft migrate
Copied!
This will create our users table for us along with a migrations table to keep track of any migrations we add later.

Creating Users

Now that we have the authentication and the migrations all migrated in, let's create our first user. Remember that we ran craft auth so we have a few new templates and controllers.
Go ahead and run the server:
terminal
1
$ python craft serve
Copied!
and head over to http://localhost:8000/register and fill out the form. You can use whatever name and email you like but for this purpose we will use:
1
Username: demo
3
Password: password!!11AA
Copied!

Migrations

We have looked at running migrations but let's look at how to create a new migration.
Now that we have our authentication setup and we are comfortable with migrating our application, let's create a new migration where we will store our posts.
Our posts table should have a few obvious columns that we will simplify for this tutorial part.

Craft Command

Not surprisingly, we have a command to create migrations. You can read more about Database Migrations here but we'll simplify it down to the command and explain a little bit of what's going on:
terminal
1
$ python craft migration create_posts_table --create posts
Copied!
This command simply creates the start of a migration file that we will use to create the posts table. By convention, table names should be plural (and model names should be singular but more on this later).
This will create a migration in the databases/migrations folder. Let's open that up and starting on line 6 we should see something that looks like:
databases/migrations/20YY:MM:DD:ABCDEF:create:posts:table.py
1
def up(self):
2
"""
3
Run the migrations.
4
"""
5
with self.schema.create('posts') as table:
6
table.increments('id')
7
table.timestamps()
Copied!
Lets add a title, an author, and a body to our posts tables.
databases/migrations/2018:01:09:043202:create:posts:table.py
1
def up(self):
2
"""
3
Run the migrations.
4
"""
5
with self.schema.create('posts') as table:
6
table.increments('id')
7
table.string('title')
8
9
table.integer('author_id').unsigned()
10
table.foreign('author_id').references('id').on('users')
11
12
table.string('body')
13
table.timestamps()
Copied!
This should be fairly straight forward but if you want to learn more, be sure to read the Database Migrations documentation.
Now we can migrate this migration to create the posts table
terminal
1
$ python craft migrate
Copied!

Models

Now that we have our tables and migrations all done and we have a posts table, let's create a model for it.
Models in Masonite are a bit different than other Python frameworks. Masonite uses an Active Record ORM. Models and migrations are separate in Masonite. Our models will take shape of our tables regardless of what the table looks like.

Creating our Model

Again, we can use a craft command to create our model:
terminal
1
$ python craft model Post
Copied!
Notice we used the singular form for our model. By default, Masonite ORM will check for the plural name of the class in our database (in this case posts) by assuming the name of the table is the plural word of the model name. We will talk about how to specify the table explicitly in a bit.
The model created now resides inside app/models/Post.py and when we open it up it should look like:
app/models/Post.py
1
"""Post Model."""
2
from masoniteorm.models import Model
3
4
class Post(Model):
5
pass
Copied!
Simple enough, right? Like previously stated, we don't have to manipulate the model. The model will take shape of the table as we create or change migrations.

Table Name

Again, the table name that the model is attached to is the plural version of the model name but if you called your table something different such as "user_posts" instead of "posts" we can specify the table name explicitly:
app/Post.py
1
"""Post Model."""
2
from masoniteorm.models import Model
3
4
class Post(Model):
5
__table__ = 'user_posts'
Copied!

Mass Assignment

Masonite ORM by default protects against mass assignment as a security measure so we will explicitly need to set what columns we would like to be fillable (this way we can pass the column names into the create and update methods later).
app/Post.py
1
"""A Post Database Model."""
2
from masoniteorm.models import Model
3
4
class Post(Model):
5
__fillable__ = ['title', 'author_id', 'body']
Copied!

Relationships

The relationship is pretty straight forward here. Remember that we created a foreign key in our migration. We can create that relationship in our model like so:
app/models/Post.py
1
"""Post Model."""
2
from masoniteorm.models import Model
3
from masoniteorm.relationships import belongs_to
4
5
class Post(Model):
6
__fillable__ = ['title', 'author_id', 'body']
7
8
@belongs_to('author_id', 'id')
9
def author(self):
10
from app.models.User import User
11
return User
Copied!
Because of how Masonite does models, some models may rely on each other so it is typically better to perform the import inside the relationship like we did above to prevent any possibilities of circular imports.
We won't go into much more detail here about different types of relationships but to learn more, refer to Masonite ORM Relationships documentation.

Designing Our Blog

Let's setup a little HTML so we can learn a bit more about how views work. In this part we will setup a really basic template in order to not clog up this part with too much HTML but we will learn the basics enough that you can move forward and create a really awesome blog template (or collect one from the internet).
Now that we have all the models and migrations setup, we have everything in the backend that we need to create a layout and start creating and updating blog posts.
We will also check if the user is logged in before creating a template.

The Template For Creating

The URL for creating will be located at /blog/create and will be a simple form for creating a blog post
templates/blog.html
1
<form action="/blog/create" method="POST">
2
{{ csrf_field }}
3
4
<input type="name" name="title">
5
<textarea name="body"></textarea>
6
</form>
Copied!
Notice here we have a {{ csrf_field }} below the <form> open tag. Masonite comes with CSRF protection so we need a token to render the hidden field with the CSRF token.
Now we need to make sure the user is logged in before creating this so let's change up our template a bit:
1
<div data-gb-custom-block data-tag="if">
2
3
<form action="/blog/create" method="POST">
4
{{ csrf_field }}
5
6
<label> Title </label>
7
<input type="name" name="title"><br>
8
9
<label> Body </label>
10
<textarea name="body"></textarea>
11
12
<input type="submit" value="Post!">
13
</form>
14
15
<div data-gb-custom-block data-tag="else">
16
17
<a href="/login">Please Login</a>
18
19
</div>
Copied!
auth() is a view helper function that either returns the current user or returns None.
Masonite uses Jinja2 templating so if you don't understand this templating, be sure to Read Their Documentation.

Static Files

For simplicity sake, we won't be styling our blog with something like Bootstrap but it is important to learn how static files such as CSS works with Masonite so let's walk through how to add a CSS file and add it to our blog.
Firstly, head to storage/static/ and make a blog.css file and throw anything you like in it. For this tutorial we will make the html page slightly grey.
storage/static/blog.css
1
html {
2
background-color: #ddd;
3
}
Copied!
Now we can add it to our template like so right at the top:
1
<link href="/static/blog.css" rel="stylesheet">
2
3
<div data-gb-custom-block data-tag="if">
4
5
<form action="/blog/create" method="POST">
6
{{ csrf_field }}
7
8
<label> Title </label>
9
<input type="name" name="title"><br>
10
11
<label> Body </label>
12
<textarea name="body"></textarea>
13
14
<input type="submit" value="Post!">
15
</form>
16
17
<div data-gb-custom-block data-tag="else">
18
19
<a href="/login">Please Login</a>
20
21
</div>
Copied!
That's it. Static files are really simple. It's important to know how they work but for this tutorial we will ignore them for now and focus on more of the backend.
Javascript files are the same exact thing:
1
<link href="/static/blog.css" rel="stylesheet">
2
3
<div data-gb-custom-block data-tag="if">
4
5
<form action="/blog/create" method="POST">
6
{{ csrf_field }}
7
8
<label> Title </label>
9
<input type="name" name="title"><br>
10
11
<label> Body </label>
12
<textarea name="body"></textarea>
13
14
<input type="submit" value="Post!">
15
</form>
16
17
<div data-gb-custom-block data-tag="else">
18
19
<a href="/login">Please Login</a>
20
21
</div>
22
23
<script src="/static/script.js"></script>
Copied!
For more information on static files, checkout the Static Files documentaton.

The Controller For Creating And The Container

Notice that our action is going to /blog/create so we need to direct a route to our controller method. In this case we will direct it to a store method.
Let's open back up the routes/web.py file and create a new route. Just add this to the ROUTES list:
routes/web.py
1
from masonite.routes import Route
2
# ...
3
ROUTES = [
4
# ...
5
Route.post('/blog/create', '[email protected]')
6
]
Copied!
and create a new store method on our controller:
app/controllers/BlogController.py
1
...
2
def show(self, view: View):
3
return view.render('blog')
4
5
# New store Method
6
def store(self):
7
pass
Copied!
Now notice above in the form we are going to be receiving 2 form inputs: title and body. So let's import the Post model and create a new post with the input.
app/controllers/BlogController.py
1
from app.models.Post import Post
2
from masonite.request import Request
3
# ...
4
5
def store(self, request: Request):
6
Post.create(
7
title=request.input('title'),
8
body=request.input('body'),
9
author_id=request.user().id
10
)
11
12
return 'post created'
Copied!
Notice that we now used request: Request here. This is the Request object. Where did this come from? This is the power and beauty of Masonite and your first introduction to the Service Container. The Service Container is an extremely powerful implementation as allows you to ask Masonite for an object (in this case Request) and get that object. This is an important concept to grasp so be sure to read the documentation further.
Also notice we used an input() method. Masonite does not discriminate against different request methods so getting input on a GET or a POST request are done exactly the same way by using this input method.
Go ahead and run the server using craft serve again and head over to http://localhost:8000/blog and create a post. This should hit the /blog/create route with the POST request method and we should see "post created".

Showing Our Posts

Lets go ahead and show how we can show the posts we just created. Now that we are more comfortabale using the framework, in this part we will create 2 new templates to show all posts and an individual post.

Creating The Templates

Let's create 2 new templates.
  • templates/posts.html
  • templates/single.html
Let's start with showing all posts

Creating The Controller

Let's create a controller for the posts to separate it out from the BlogController.
terminal
1
$ python craft controller Post
Copied!
Great! So now in our show method we will show all posts and then we will create a single method to show a specific post.

Show Method

Let's get the show method to return the posts view with all the posts:
app/controllers/PostController.py
1
from app.models.Post import Post
2
3
...
4
5
def show(self, view: View):
6
posts = Post.all()
7
8
return view.render('posts', {'posts': posts})
Copied!

Posts Route

We need to add a route for this method:
routes/web.py
1
Route.get('/posts', '[email protected]')
Copied!

Posts View

Our posts view can be very simple:
templates/posts.html
1
<div data-gb-custom-block data-tag="for">
2
3
{{ post.title }}
4
<br>
5
{{ post.body }}
6
<hr>
7
8
</div>
Copied!
Go ahead and run the server and head over to http://localhost:8000/posts route. You should see a basic representation of your posts. If you only see 1, go to http://localhost:8000/blog to create more so we can show an individual post.
Showing The Author
Remember we made our author relationship before. Masonite ORM will take that relationship and make an attribute from it so we can display the author's name as well:
templates/posts.html
1
<div data-gb-custom-block data-tag="for">
2
3
{{ post.title }} by {{ post.author.name }}
4
<br>
5
{{ post.body }}
6
<hr>
7
8
</div>
Copied!
Let's repeat the process but change our workflow a bit.

Single Post Route

Next we want to just show a single post. We need to add a route for this method:
routes/web.py
1
Route.get('/post/@id', '[email protected]')
Copied!
Notice here we have a @id string. We can use this to grab that section of the URL in our controller in the next section below. This is like a route URL capture group.

Single Method

Let's create a single method so we show a single post.
app/controllers/PostController.py
1
from app.models.Post import Post
2
from masonite.request import Request
3
from masonite.view import View
4
...
5
6
def single(self, view: View, request: Request):
7
post = Post.find(request.param('id'))
8
9
return view.render('single', {'post': post})
Copied!
We use the param() method to fetch the id from the URL. Remember this key was set in the route above when we specified the @id
For a real application we might do something like @slug and then fetch it with request().param('slug').

Single Post View

We just need to display 1 post so lets just put together a simple view:
templates/single.html
1
{{ post.title }}
2
<br>
3
{{ post.body }}
4
<hr>
Copied!
Go ahead and run the server and head over the http://localhost:8000/post/1 route and then http://localhost:8000/post/2 and see how the posts are different.

Updating and Deleting Posts

By now, all of the logic we have gone over so far will take you a long way so let's just finish up quickly with updating and deleting posts. We'll assume you are comfortable with what we have learned so far so we will run through this faster since this is just more of what were doing in the previous parts.

Update Controller Method

Let's just make an update method on the PostController:
app/controllers/PostController.py
1
def update(self, view: View, request: Request):
2
post = Post.find(request.param('id'))
3
4
return view.render('update', {'post': post})
5
6
def store(self, request: Request):
7
post = Post.find(request.param('id'))
8
9
post.title = request.input('title')
10
post.body = request.input('body')
11
12
post.save()
13
14
return 'post updated'
Copied!
Since we are more comfortable with controllers we can go ahead and make two at once. We made one that shows a view that shows a form to update a post and then one that actually updates the post with the database.

Create The View

  • templates/update.html
Untitled
1
<form action="/post/{{ post.id }}/update" method="POST">
2
{{ csrf_field }}
3
4
<label for="">Title</label>
5
<input type="text" name="title" value="{{ post.title }}"><br>
6
7
<label>Body</label>
8
<textarea name="body">{{ post.body }}</textarea><br>
9
10
<input type="submit" value="Update">
11
</form>
Copied!

Create The Routes:

Remember we made 2 controller methods so let's attach them to a route here:
routes/web.py
1
Route.get('/post/@id/update', '[email protected]'),
2
Route.post('/post/@id/update', '[email protected]'),
Copied!
That should be it! We can now update our posts.

Delete Method

Let's expand a bit and make a delete method.
app/controllers/PostController.py
1
from masonite.request import Request
2
...
3
4
def delete(self, request: Request):
5
post = Post.find(request.param('id'))
6
7
post.delete()
8
9
return 'post deleted'
Copied!

Make the route:

routes/web.py
1
Route.get('/post/@id/delete', '[email protected]'),
Copied!
Notice we used a GET route here, It would be much better to use a POST method but for simplicity sake will assume you can create one by now. We will just add a link to our update method which will delete the post.

Update the Template

We can throw a delete link right inside our update template:
templates/update.html
1
<form action="/post/{{ post.id }}/update" method="POST">
2
{{ csrf_field }}
3
4
<label for="">Title</label>
5
<input type="text" name="title" value="{{ post.title }}"><br>
6
7
<label>Body</label>
8
<textarea name="body">{{ post.body }}</textarea><br>
9
10
<input type="submit" value="Update">
11
12
<a href="/post/{{ post.id }}/delete"> Delete </a>
13
</form>
Copied!
Great! You now have a blog that you can use to create, view, update and delete posts! Go on to create amazing things!
Last modified 1mo ago