Path ('Polls/', Include ('App - Urls') )
Path ('Polls/', Include ('App - Urls') )
Creating Project
$ django-admin startproject <project name>
2. Development server
$ python manage.py runserver -- run this command from Project directory
3. Creating app
$ python manage.py startapp <app name>-- run this command from project home directory.
After creating the app specify the app name in project/settings.py file’s INSTALLEDAPPS location.
//project/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('app.urls')),
path('admin/', admin.site.urls), ]
BooleanField class BooleanField(**options) A true/false field. The default form widget for
this field is a CheckboxInput.
TextField class TextField(**options) A large text field. The default form widget for
this field is a Textarea.
1. first_name = models.CharField(max_length=50) # for creating varchar column
2. release_date = models.DateField() # for creating date column
3. num_stars = models.IntegerField() # for creating integer column
Field Options
Each field requires some arguments that are used to set column attributes. For example, CharField requires mac_length to
specify varchar database.
Field Particulars
Options
Choices An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.
Default The default value for the field. This can be a value or a callable object.
help_text Extra "help" text to be displayed with the form widget. It's useful for documentation even if your field
isn't used on a form.
primary_key This field is the primary key for the model.
Example:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
First we’ll need to create a user who can login to the admin site. Run
the following command:
Username: admin
The fifinal step is to enter your password. You will be asked to enter
your password twice, the second time as a
Password: **********
B. Now open admin site and enter the username and password
Localhost:8000/admin
Only one more thing to do: we need to tell the admin that model objects have an admin interface. To do
this,
polls/admin.py
admin.site.register(Question)
8. Writing VIEWS
A view is a “type” of Web page in your Django application that generally serves a specific function
and has a specific template.
In Django, web pages and other content are delivered by views. Each view is represented by a
Python function (or method, in the case of class-based views). Django will choose a view by
examining the URL that’s requested (to be precise, the part of the URL after the domain name).
//project/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('app.urls')),
path('admin/', admin.site.urls), ]
Each view is responsible for doing one of two things: returning an HttpResponse object containing the
content for the requested page, or raising an exception such as Http404. The rest is up to you. Your view
can read records from a database, or not. It can use a template system such as Django’s – or a third-
party Python template system – or not. It can generate a PDF fifile, output XML, create a ZIP fifile on the
flfly, anything you want, using whatever Python libraries you want. All Django wants is that
HttpResponse. Or an exception.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:3]
return HttpResponse(output)
Here index is a function based view which will retrieve the latest 3 questions from the Question table
from the Database.
There’s a problem here, though: the page’s design is hard-coded in the view. If you want to change the
way the page looks, you’ll have to edit this Python code. So let’s use Django’s template system to
separate the design from Python by creating a template that the view can use.
A. create a directory called templates in your app (ex:polls) directory. Django will look for templates
in there.
NOTE: Your project’s TEMPLATES setting describes how Django will load and render templates. The
default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By
convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.
B. Within the templates directory you have just created, create another directory with app name
(ex:called polls), and within that create a template file (ex:called index.html.)
C. And write the template code in that template file you have created
Example: index,html
<html>
<body>
{% if latest_question_list %}
<ul>
{% endfor %}
</ul>
{% else %}
{% endif %}
</body>
</html>
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:3]
template = loader.get_template('polls/index.html')
A shortcut: render()
It’s a very common idiom to load a template, fifill a context and return an HttpResponse object with the
result of the rendered template. Django provides a shortcut called render ()
eXampl:
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
The render() function takes the request object as its fifirst argument, a template name as its second
argument and a dictionary as its optional third argument. It returns an HttpResponse object of the given
template rendered with the given context.
Exxample:
def detail(request,question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
A shortcut: get_object_or_404()
It’s a very common idiom to use get() and raise Http404 if the
object doesn’t exist. Django provides a shortcut.
Here’s the detail() view, rewritten:
Listing 24: polls/views.py
from django.shortcuts import get_object_or_404, render
from .models import Question
# ...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question':
question})
The get_object_or_404() function takes a Django model as its
fifirst argument and an arbitrary number of
keyword arguments, which it passes to the get() function of the
model’s manager. It raises Http404 if the object
doesn’t exist.
Templates :
A template contains the static parts of the desired HTML output as well as some special syntax
describing how dynamic content will be inserted.Django ships built-in backends for its own template
system, creatively called the Django template language (DTL).
Django defifines a standard API for loading and rendering templates regardless of the backend. Loading
consists of finding the template for a given identifier and prepossessing it, usually compiling it to an in-
memory representation. Rendering means interpolating the template with context data and returning
the resulting string.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
BACKEND is a dotted Python path to a template engine class implementing Django’s template backend API.
The built in backends are django.template.backends.django.DjangoTemplates and django.template.
backends.jinja2.Jinja2.
Since most engines load templates from files, the top-level configuration for each engine contains two
common settings:
• DIRS defines a list of directories where the engine should look for template source files, in search order.
• APP_DIRS tells whether the engine should look for templates inside installed applications. Each backend
defifines a conventional name for the subdirectory inside applications where its templates should be stored.
While uncommon, it’s possible to configure several instances of the same backend with different options. In
that case you should define a unique NAME for each engine. OPTIONS contains backend-specifific settings.