Django¶
easy Python web framework
resources¶
- official doc
installation¶
pip3 install django
basic commands¶
manage.pyis like theartisanof Laravel- creation
django-admin startproject mysite
- run server
- (in root)
python manage.py runserverthen go to http://127.0.0.1:8000/
- (in root)
- create app
python manage.py startapp app1
routing¶
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app1.urls')), # route to app1's urls.py
path('doc', TemplateView.as_view(template_name='doc.html')), # return template directly
path('', views.index, name='index'), # use function index() in file views
]
views¶
urls.py is Laravel's web.php
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'), # views.index = file.function
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
app1 is an app you created and added in settings.py INSTALLED_APPSindex.html located in app1/templates/app1/index.htmlwhy not put in
templates/index.html?
Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.
settings¶
remove csrf protection¶
settings.py MIDDLEWARE comment 'django.middleware.csrf.CsrfViewMiddleware'
migration¶
Note that there will be several migrations created by django before you've done anything.
- create migration
- alter
app1/models.pyand runpython manage.py makemigrations app1, will generate migration files atapp1/migrationfor you- equivalent to Laravel's
php artisan migrateexcept you only have to alter the database format directly without worrying about the create table drop column syntax
- equivalent to Laravel's
- alter
- print migration file
python manage.py sqlmigrate app1 0001
- run migration
python manage.py migrate- equivalent to Laravel's
php artisan migrate
- equivalent to Laravel's
- migration status
python smanage.py showmigrations- eq to Laravel's
php artisan migrate:status --planto print in list
- eq to Laravel's
- reset your database
python manage.py flush