Django Tutorial for Beginners

This is a brief tutorial for Django setup, only critical steps are noted, it aims serve as a quick reference when you want to setup a Django project or when yo forget some part of it. For more detailed information, please see official tutorial

Create a Project

  • $ django-admin startproject [project name]

Project Structure

1
2
3
4
5
6
7
mysite/
manage.py
mysite/
__init__.py(empty file, indicates it’s a package)
settings.py(configuration for this project)
urls.py(url declarations)
wsgi.py

Run Server

  • python manage.py runserver ([port]/[url:port])

Projects vs App

  • App is a web application (blog system, database)
  • Project is a collection of apps for a particular website
  • Project can contains multiple apps, an app can be in multiple projects

Create App

  • python manage.py startapp [app name]

App Structure

1
2
3
4
5
6
7
8
9
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

Here, we should write the view part first

Step 1:

  • Create urls.py in your app
  • Map the url (in urls.py)
    e.g.: url(r’^$’, views.index, name=‘index’)
  • Include that in project urls
    e.g.: url(r’calculator/‘, include(‘calculator.urls’))

URL routing with parameters

  • url(r’^delete_item/(?P\d+)$’, shared_todo_list.views.delete_item)

Creating Models

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class PostModel(models.Model):
content = models.CharField(max_length=100)
id = models.AutoField(null=False, primary_key=True)
TYPE_CHOICE = (
("IMG", "image"),
("TEXT", "text"),
)
type = models.CharField(max_length=100, choices=TYPE_CHOICE)
img = models.ImageField(upload_to="grumblr/static/", max_length=500, blank=True)
author = models.ForeignKey(UserModel, default="")
update_date = models.DateTimeField(auto_now=True)
create_date = models.DateTimeField(auto_now_add=True)
likes = models.IntegerField(default=0)
dislikes = models.IntegerField(default=0)
comments = models.ManyToManyField("CommentModel")

Creating Form and form Validation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class RegistrationForm(forms.Form):
username = forms.CharField(max_length=20)
first_name = forms.CharField(max_length=20)
last_name = forms.CharField(max_length=20)
email = forms.CharField(max_length=40, label='Email')
password = forms.CharField(max_length=20,
label='Password',
widget=forms.PasswordInput())
password_confirm = forms.CharField(max_length=20,
label='Confirm password',
widget=forms.PasswordInput())
age = forms.IntegerField(label="Age")
bio = forms.CharField(label="Short Bio", max_length=200)
avatar = forms.ImageField(required=False)

def clean(self):
cleaned_data = super(RegistrationForm, self).clean()

username = cleaned_data.get('username')
password = cleaned_data.get('password')
password_confirm = cleaned_data.get('password_confirm')
if password and password_confirm and password != password_confirm:
raise forms.ValidationError("Passwords did not match.")
if len(User.objects.filter(username=username)) > 0:
raise forms.ValidationError("User already exist")

Form validation and Model Referencing

1
2
3
4
5
6
7
8
9
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
avatar = form.cleaned_data['avatar']
new_user = User(username=form.cleaned_data['username'], last_name=form.cleaned_data['last_name'],
first_name=form.cleaned_data['first_name'], email=form.cleaned_data['email'],
password=form.cleaned_data['password'],
avatar=avatar, bio=form.cleaned_data['bio'], age=form.cleaned_data['age'])
new_user.set_password(form.cleaned_data['password'])
new_user.save()

Basic Template Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
\{\% extends "profile_base.html" %}
\{\% load staticfiles %}
\{\% block headers %}
<title>Follow</title>
<link href="\{\% static "css/bootstrap.min.css" %}" rel="stylesheet">
<link href="\{\% static "css/nav.css" %}" rel="stylesheet">
<link href="\{\% static "css/profile.css" %}" rel="stylesheet">
<link href="\{\% static "css/feed.css" %}" rel="stylesheet">
<link href="\{\% static "css/follow.css" %}" rel="stylesheet">
<script src="\{\% static "js/jquery-3.1.0.min.js" %}"></script>
<script src="\{\% static "js/bootstrap.min.js" %}"></script>
<script src="\{\% static "js/feed.js" %}"></script>

\{\% endblock %}
\{\% block content %}
<ol id="follow-list">
\{\% for u in data.list %}
<li class="follow-item">
<div>
<a class="follow-avatar-container" href="\{\% url 'user' user_id=u.id %}">
\{\% if u.avatar %}
<img class="follow-avatar" src="../../../">
\{\% else %}
<img class="follow-avatar" src="\{\% static "img/avatar.jpg" %}">
\{\% endif %}
</a>
<div class="follow-content-container">
<div class="follow-first-line">
<a class="follow-author" href="\{\% url 'user' user_id=u.id %}">
</a>
</div>
<div class="follow-second-line">
<p class="feed-content-text">Age: &nbsp; Bio: </p>
</div>
</div>
</div>
</li>

\{\% endfor %}

</ol>
\{\% endblock %}