Writing your first Django Masonite app, part 1
Following tutorial01
check your installation.
In Django, you run the following command to check your Django version.
$ python -m django --version
In Masonite, you run
$ craft -v
Creating a project
In Django.
$ django-admin startproject mysite
In Masonite
$ craft new mysite
The development server
In Django.
$ python manage.py runserver
In Masonite, We need to install before running the server.
Running the WSGI Server
Host and Port
$ craft install
# then now we can run the server.
$ craft serve
Creating the Polls app
Until this point, Django and Masonite were not so different, just running some commands against your code. From this point, the difference will be clear.
running
In Django.
$ python manage.py startapp polls
In Masonite, we do not need this.
$
Write your first view
In Django.
# polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
In Masonite. The Controllers works like "view" in Django.
First We have to add new Controllers.
$ craft controller Polls
This command generates "app/http/controllers/PollsController.py"
""" A PollsController Module """
class PollsController:
"""PollsController
"""
def show(self):
pass
Let's edit this as follow
""" A PollsController Module """
class PollsController:
"""PollsController
"""
def index(self):
return "Hello, world. You're at the polls index."
In Django urls.py handle the request from the user.
# mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
#polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
In Masonite, the route handles the request. By default, you have routes
/web.py in your project.
Routing
"""Web Routes."""
from masonite.routes import Get, Post
ROUTES = [
Get().route('/', 'WelcomeController@show').name('welcome'),
]
The request is "http://localhost:8000/polls/" so we have to handle /polls/
in our route. Masonite handle the HTTP Verbs and match with a controller.
"""Web Routes."""
from masonite.routes import Get, Post
ROUTES = [
Get().route('/', 'WelcomeController@show').name('welcome'),
Get().route('/polls/', 'PollsController@index'),
]
make sure you are running the server
$ craft serve -r
Then you can access your page.
We finished successfully the tutorial01 of Django tutorial with Masonite.
Top comments (0)