Django Cheatsheet
Django Cheatsheet
python -m django --version
Note: Don’t use - in project name
django-admin startproject your_project_name
It creates following directory structure
└── your_project_name
├── manage.py
└── your_project_name
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
These files are:
python manage.py runserver [ip-address:port]
If no address is given, it will run server on http://localhost:8000/.
python manage.py startapp your_app_name
It creates following directory structure
├── your_app_name
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
Note: Apps can live anywhere on your python path.
An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
Here is simplest possible view in django
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello django!!")
Create a urls.py file in your app’s directory and add following lines
from django.urls import path
from . import views
urlpatterns = [
path('url_to_view', 'your_view', name='name_for_your_url')
]
name attribute is used to refer your view from somewhere else in your code. Even if you change the actual url, name will still refer to same view. For example
In Code
password_url = reverse('name_for_your_url')
In template
<p>Please go <a href="{% url 'name_for_url' %}">here</a></p>
Add following lines in your project/urls.py
from django.urls import include
urlpatterns = [
path('sub_url_for_your_app', include('your_app.urls'))
]
include() allows referencing other URLConfs