Django 101 By: Jason Sumner
Django Overview Django was started in 2003, released under BSD in 2005, and the Django Software Foundation was established in Object Relational Mapper engine that handles Models = relational database schema (models.py) Views = http request and web template system (views.py) Controller = Regex URL dispatcher (urls.py) Django Packages - Allows for third party components to be added available through pip CSRF, built in authentication, strong password storage, admin portal, and other out of the box features.
Preparation Download and Install Python 3.4 Install pip: $ sudo easy_install pip Install virtualenv $ pip install virtualenv
Create and Activate the Virtual Environment Create directory for your Django project and enter virtual environment $ virtualenv barcampdemo $ cd barcampdemo $ source bin/activate
Install Packages Install Django and database utility $ pip install django south $ pip freeze
Create Project and Establish Database Create new Django project and change directories $ django-admin.py startproject www $ cd www Establish Database $ python3 manage.py migrate
Create Admin User Create User $ python3 manage.py createsuperuser Start Server $ python3 manage.py runserver
Let’s Play With Some Code
Create first application Create an application called “signup” $ python3 manage.py startapp signup Notice the new folder and file structure created
settings.py Changes Add the following code to establish a templates folder: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates’, 'DIRS': [os.path.join(BASE_DIR, '_templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug’, 'django.template.context_processors.request’, 'django.contrib.auth.context_processors.auth’, 'django.contrib.messages.context_processors.messages’, ], }, }, ]
settings.py Changes Add following code to establish a static folder: # Need when relocate to a web host # STATIC_ROOT = os.path.join(BASE_DIR, '_static’) STATICFILES_DIRS = ( os.path.join(BASE_DIR, '_static'), ) Change following lines: DEBUG = False ALLOWED_HOSTS = ['localhost',' '] Add new application to INSTALLED_APPS: 'signup’, 'signup’,
views.py Modify views.py from django.shortcuts import render, render_to_response, RequestContext from django.contrib import messages def home(request): # Render page return render_to_response(”index.html", locals(), context_instance=RequestContext(request)) return render(request, ”index.html", context) Create index.html landing page and signupform.html form page
models.py Models define the import uuid class signupModel(models.Model): first_name = models.CharField(max_length=120, null=False, blank=False) last_name = models.CharField(max_length=120, null=False, blank=False) _address = models. Field(max_length=120, null=False, blank=False) tech256_username = models.CharField(max_length=120, null=True, blank=True) webste_url = models.URLField(max_length=200, null=True, blank=True) # Define variables for option newsletter_no = 'NO’ newsletter_yes = 'YES’ newsletter_options = ( (newsletter_no, 'No - I hate junk '), (newsletter_yes, 'Yes - Send it to my spam account'), ) # Default database column/type and reference variables defined above newsletter_preference = models.CharField(max_length=4, choices=newsletter_options, default=newsletter_yes) talk_description = models.TextField(null=False, blank=False) active = models.BooleanField(default=True) sid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False def __str__(self): return self.sid Once defined, make the migrations: $ python3 manage.py makemigrations $ python3 manage.py migrate
forms.py Create a new file called “forms.py” under the Application folder. from django import forms from.models import signupModel class SignupForm(forms.ModelForm): class Meta: model = signupModel fields = ['first_name','last_name',' _address','tech256_use rname','webste_url','newsletter_preference’,'talk_des cription','active']
Modify views.py Modify views.py: # Create your views here. from django.shortcuts import render, render_to_response, RequestContext from django.contrib import messages from.forms import SignupForm def home(request): form = SignupForm(request.POST or None) if request.method=="POST”: if form.is_valid(): human = True save_it = form.save(commit=False) save_it.save() messages.success(request,"Thank you for registering!”) else: form = SignupForm(request.POST or None) messages.error(request,"Uh oh! Correct the errors below.") else: form = SignupForm(request.POST or None) # Render page return render_to_response(”signupform.html", locals(), context_instance=RequestContext(request)) return render(request, ”signupform.html", context)
Create Templates index.html {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% block content %}{% endblock %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% block content %}{% endblock %}signuform.html {% extends 'index.html' %} {% block content %} {% csrf_token %} {{ form.as_p }} {% endblock %}
admin.py Add the following code to register in Admin Portal from.models import signupModel class signupAdmin(admin.ModelAdmin): list_display = ["sid","first_name","last_name"," _address","tec h256_username”] class Meta: model = signupModel admin.site.register(signupModel, signupAdmin)
Apply A Template Copy over static items to _static folder. Copy HTML Code over to index.html and place form. Modify path to _static folder URL. Modify CSS to correct elements. View in Desktop and Mobile formats.
Resources HTML5 UP – “Prologue” Theme Django Project Justin Mitchell/Coding Entrepreneurs - sfXFp6DpzRcd-q4vR5qAgOZUuz8041S sfXFp6DpzRcd-q4vR5qAgOZUuz8041S sfXFp6DpzRcd-q4vR5qAgOZUuz8041S Python Django Packages -
Questions