Beginners Python Cheat Sheet PCC Django
Beginners Python Cheat Sheet PCC Django
models. projects home page can start out as a simple page with no
data. A page usually needs a URL, a view, and a template.
Defining a model
To define the models for your app, modify the file models.py that Mapping a projects URLs
was created in your apps folder. The __str__() method tells The projects main urls.py file tells Django where to find the urls.py
Django how to represent data objects based on this model. files associated with each app in the project.
from django.db import models from django.conf.urls import include, url
from django.contrib import admin
Django is a web framework which helps you build class Topic(models.Model):
interactive websites using Python. With Django you """A topic the user is learning about.""" urlpatterns = [
define the kind of data your site needs to work with, text = models.CharField(max_length=200) url(r'^admin/', include(admin.site.urls)),
and you define the ways your users can work with date_added = models.DateTimeField( url(r'', include('learning_logs.urls',
that data. auto_now_add=True) namespace='learning_logs')),
]
def __str__(self):
return self.text Mapping an apps URLs
Its usualy best to install Django to a virtual environment, An apps urls.py file tells Django which view to use for each URL in
where your project can be isolated from your other Python Activating a model the app. Youll need to make this file yourself, and save it in the
projects. Most commands assume youre working in an To use a model the app must be added to the tuple apps folder.
active virtual environment. INSTALLED_APPS, which is stored in the projects settings.py file.
from django.conf.urls import url
Create a virtual environment INSTALLED_APPS = (
--snip-- from . import views
$ python m venv ll_env 'django.contrib.staticfiles',
Activate the environment (Linux and OS X) urlpatterns = [
# My apps url(r'^$', views.index, name='index'),
$ source ll_env/bin/activate 'learning_logs', ]
)
Activate the environment (Windows) Writing a simple view
Migrating the database A view takes information from a request and sends data to the
> ll_env\Scripts\activate browser, often through a template. View functions are stored in an
The database needs to be modified to store the kind of data that
the model represents. apps views.py file. This simple view function doesnt pull in any
Install Django to the active environment data, but it uses the template index.html to render the home page.
(ll_env)$ pip install Django $ python manage.py makemigrations learning_logs
$ python manage.py migrate from django.shortcuts import render