项目作者: warisali2

项目描述 :
Django Cheatsheet
高级语言:
项目地址: git://github.com/warisali2/django-cheatsheet.git
创建时间: 2018-04-22T12:11:20Z
项目社区:https://github.com/warisali2/django-cheatsheet

开源协议:GNU General Public License v3.0

下载


django-cheatsheet

Django Cheatsheet

Table Of Contents

Check Django Version

  1. python -m django --version

Create Django Project

Note: Don’t use - in project name

  1. django-admin startproject your_project_name

It creates following directory structure

  1. └── your_project_name
  2. ├── manage.py
  3. └── your_project_name
  4. ├── __init__.py
  5. ├── settings.py
  6. ├── urls.py
  7. └── wsgi.py

These files are:

  • Outer your_project_name Root director of your project. Just a container.
  • manage.py Django utility to interact with project.
  • Inner your_project_name Actual django app.
  • settings.py Settings for this django project.
  • urls.py URLs declarations for this django project.
  • wsgi.py Entry point for WSGI (Web Server Gateway Interface) compatible servers to serve your project.

Run Development Server

  1. python manage.py runserver [ip-address:port]

If no address is given, it will run server on http://localhost:8000/.

Create an App

  1. python manage.py startapp your_app_name

It creates following directory structure

  1. ├── your_app_name
  2. ├── admin.py
  3. ├── apps.py
  4. ├── __init__.py
  5. ├── migrations
  6. └── __init__.py
  7. ├── models.py
  8. ├── tests.py
  9. └── views.py

Note: Apps can live anywhere on your python path.

Projects vs Apps

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.

Sample View

Here is simplest possible view in django

  1. from django.http import HttpResponse
  2. def index(request):
  3. return HttpResponse("Hello django!!")

Map View to URL

Create a urls.py file in your app’s directory and add following lines

  1. from django.urls import path
  2. from . import views
  3. urlpatterns = [
  4. path('url_to_view', 'your_view', name='name_for_your_url')
  5. ]

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

  1. password_url = reverse('name_for_your_url')

In template

  1. <p>Please go <a href="{% url 'name_for_url' %}">here</a></p>

Point Root URLConf at App’s URL module

Add following lines in your project/urls.py

  1. from django.urls import include
  2. urlpatterns = [
  3. path('sub_url_for_your_app', include('your_app.urls'))
  4. ]

include() allows referencing other URLConfs