Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
django notes
#get version
python -c "import django; print(django.get_version())"
#create a project startproject mysite
#run development server
python runserver OR python runserver 8080 OR python runserver
#create databse tables from INSTALLED_APPS models
python syncdb
#create an app in the project
python startapp polls
#define model for polls in /polls/
Each model is represented by a class that subclasses django.db.models.Model.
Each model has a number of class variables, each of which represents a database field in the model.
Each field is represented by an instance of a Field class
You can use an optional first positional argument to a Field to designate a human-readable name. That’s used in a couple of introspective parts of Django, and it doubles as documentation.
Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
# Add app to project
Edit the mysite/ file again, and change the INSTALLED_APPS setting to include the string 'polls'.
# See SQL output of model (print to screen)
python sql polls
# Check for errors
python validate
#Update database with new models
python syncdb
#Interactive python/django shell
python shell
#Creating the public interface – “views.”
#Adding Users
django user login/registration
Users can be added from the admin portal or from the django API from the shell.
Under the app templates create a subdirectory called registration and add two new templates.
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
Suck a nut
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
{% endblock %}
{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<form action="" method="post">
{{ form.as_p }}
<input type="submit" value="Create the account">
{% endblock %}
#Understanding templates
>>> from django import template
>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Adrian'})
>>> print t.render(c)
My name is Adrian.
>>> c = template.Context({'name': 'Fred'})
>>> print t.render(c)
My name is Fred.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment