#install django: pip install Django==1.9.2
Applicable for: django-1.9 and python-3.4.3 /django-1.9.3 & python 2.7.
#django version check: django-admin --version
#create django project:
django-admin startproject mysite .
# Start server if project created successfully:
manage.py runserver ::check if the site is working fine (default port is 8000):
=>http://localhost:8000/ (accessible on local machine only)
manage.py runserver 10.0.0.036:8081 =>http://10.0.0.36:8081 (accessible from any system on the network)
"
It worked!
Congratulations on your first Django-powered page.
"
# Check any issue with server coding:
manage.py check
# create application
manage.py startapp bookmarks
# Note:
A. Server run: Django starts web server listener at the specified port with loading the server configuration from the file settings.py. manage.py has information where the settins.py is located.
B. Connection to the server host at the listening port directs the call to the the listener code. The redirection is done by the system's network layer. The system network layer and the server code works closely.
The incoming connection request comes to the network layer of the system. Network layer -> Django framework which coordinates the network layer on one side and the code layer on the other side.
Framework connects the request to the file 'urls.py'. This file sends the request to the properly mapped urls or views.
# Basic urls.py configuration: (main_function to be defined in the file views.py)
from django.conf.urls import url
from bookmarks.views import *
urlpatterns = [
url(r'^$', main_page),
]
# main_page function in views.py
# Create your views here.
from django.http import HttpResponse
def main_page(request):
output = '''
<html>
<head><title>%s</title></head>
<body>
<h1>%s</h1><p>%s</p>
</body>
</html>
''' % (
'Django Bookmarks',
'Welcome to Django Bookmarks',
'Where you can store and share bookmarks!'
)
return HttpResponse(output)
===== This completes basic modifiable server setup =====
# Setup database
# Create essential tables for already specified defaults apps in:
By default,
INSTALLED_APPS contains the following apps, all of which come with Django:
These applications are included by default as a convenience for the common case.
=> command: manage.py migrate
Note: to create table for an app, the models.py must have the table definition. Above applications already has the table definitions in their corresponding models.
# Create tables for new app 'bookmarks': Modify the file models.py
Now add the new app to the INSTALLED_APPS configuration:
'bookmarks.apps.BookmarksConfig',
AS:
INSTALLED_APPS = [
'bookmarks.apps.BookmarksConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
=> After each modification of model the following two command must run:
manage.py makemigrations bookmarks(the app name)
# Check what SQL will run when 'manage.py migrate will run':
=>manage.py sqlmigrate bookmarks 0001
manage.py migrate
# Now database is setup. Play around the database with django shell:
=>manage.py shell
>>> from bookmarks.models import *
>>> link1 = Link(url='http://www.packtpub.com/')
>>> link1.save()
>>> link2 = Link(url='http://www.example.com/')
>>> link2.save()
>>> link2.url
>>> link2.url = 'http://www.google.com/'
>>> link2.save()
To get a list of all available Link objects, type the following:
>>> links = Link.objects.all()
>>> for link in links:
... print link.url
...
To get an object by ID, type the following:
>>> Link.objects.get(id=1)
<Link: Link object>
Finally, to delete a link, use the following:
>>> link2.delete()
>>> Link.objects.count()
# User management:
Fortunately for us, management of user accounts is so common that Django comes with a user model ready for us to use. This model contains fields that are often associated with user accounts, such as username, password and email and so on. The model is called User and it's located in the django.contrib.auth.models package.
To explore the contents of this model, open the interactive console and type
the following:
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[] : The user list is empty because no user is created.
# Create super user:
manage.py createsuperuser
Provide the asked in formation
Check on the shell:
c:\test>manage.py shell
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> User.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'User' is not defined
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: admin>]
>>>
You can examine the fields of User objects by using the dir function:
>>> user = User.objects.get(id=1)
>>> dir(user)
You will get a very long list of attributes. Among them you will find the username, email address and password. Good news! This model fulfills our needs. Django provides all the necessary attributes for our user objects, and we can use directly use the User model directly without any extra code.
# create user link table for relational database:
insert the code below in the models file:
from django.contrib.auth.models import User
class Bookmark(models.Model):
title = models.CharField(maxlength=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
Updated modelds.py
from django.db import models
from django.contrib.auth.models import User
class Link(models.Model):
url = models.URLField(unique=True)
class Bookmark(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
Then run
manage.py makemigrations bookmarks
manage.py migrate
(the above two command need to run because models.py updated)
# Putting views in templates folder
-create 'templates' folder in the app folder (bookmarks)
#Note:
Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures aDjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.
# create a file called main_page.html in the templates folder with the
following content:
<html>
<head>
<title>{{ head_title }}</title>
</head>
<body>
<h1>{{ page_title }}</h1>
<p>{{ page_body }}</p>
</body>
</html>
# update the file views.py:
from django.http import HttpResponse
from django.template import RequestContext, loader
def main_page(request):
template = loader.get_template('main_page.html')
variables = RequestContext(request, {
'head_title': 'Django Bookmarks',
'page_title': 'Welcome to Django Bookmarks',
'page_body': 'Where you can store and share bookmarks!'
})
output = template.render(variables)
return HttpResponse(output)
# Django forms:
A. without django form:
step-1: app's html page: create form tag on required html page of the django app and specify action=<any_page_name> and method=<get or post>
<form action="/search1/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
Note: any_page_name does not need to exist for django powered site
step-2: site's urls.py: add any_page_name and and any_function_name for url redirection/filtering/validation to the urls.py
Example: url(r'^search1/$', search),
Note:
1. ^$ => just server url, i.e http://localhost:800, because ^ => start
and $ => end : means empty string
2. The functions in views.py represent a html page, because after executing that function a page is sent to the browser with that (function name) name in the browser address. example: http://localhost:8000/my_function will directly call the python function 'my_function' in the file views.py
3. The definitions in views.py are also called 'views'. Creating a view or page in django powered server is same as creating or calling a function from views.py
step-3: app's views.py: add definition of the function any_function_name specified in site's urls.py
Example:
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)