0% found this document useful (0 votes)
83 views11 pages

Path ('Polls/', Include ('App - Urls') )

The document discusses how to create and configure a Django project and its components. It covers: 1. Creating a project with django-admin and running the development server. 2. Creating apps and configuring them in settings.py. 3. Setting up app URLs and connecting them to the project URLs. 4. Configuring the database by modifying settings.py and running migrations. 5. Creating models within apps to define database tables and fields.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views11 pages

Path ('Polls/', Include ('App - Urls') )

The document discusses how to create and configure a Django project and its components. It covers: 1. Creating a project with django-admin and running the development server. 2. Creating apps and configuring them in settings.py. 3. Setting up app URLs and connecting them to the project URLs. 4. Configuring the database by modifying settings.py and running migrations. 5. Creating models within apps to define database tables and fields.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

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.

Projects vs. apps


What’s the difference between a project and an app? An app is a Web application that does
something – e.g., a Weblog system, a database of public records or a small poll app. A
project is a collection of configuration and apps for a particular website. A project can
contain multiple apps. An app can be in multiple projects.
4. Creating the Views for App
a. Open app folder/views.py and write the code as follows(example code )
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
b. To call the view, we need to map it to a URL - and for this we need a URLconf. To
create a URLconf in the app directory, create a file called urls.py.
//urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'), ]
c. The next step is to point the root URLconf at the apps.urls module. In
project/urls.py, add an import for django.urls.include and insert an include() in the
urlpatterns list, so you have:

//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), ]

NOTE: path() syntax


path(route,view)
path() argument: route
route is a string that contains a URL pattern. When processing a request, Django starts at
the first pattern in urlpatterns and makes its way down the list, comparing the requested
URL against each pattern until it finds one that matches.
path() argument: view
When Django finds a matching pattern, it calls the specifified view function with an
HttpRequest object as the first argument and any “captured” values from the route as
keyword arguments.
5. Creating DATABASE for Project.
Default Database which support by the django Is SQLite.
If we want to change the database settings we need to follow the
following steps:
a. open up mysite/settings.py.—which is the main configuration file
for the total project.
b. For connecting Mysql database first we need to install mysqlclient
dependency using pip install mysqlclient and then change the
settings related to DATABASE in settings.py file as follows>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database name',
'USER': 'root',
'PASSWORD': "",
'HOST': "", // it wil take local host
'PORT': "",// it will take default port
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}}}

c. so we need to create the tables in the database before we can


use them. To do that, run the following command:

$ python manage.py migrate


NOTE: now our database setting is completed and we are ready to
write the models for our applications (i.e. apps)

6. Creating MODELS for APPS


NOTE: models which we create will be converted into tables
in MYSQL database as appname_model name As table
a. To create model for any app open models.py file and write
the code.
b. Create a class with properties : the class name is
model(table) and properties will become columns in the table
Django Model fields:
Django Model Fields
The fields defined inside the Model class are the columns name of the mapped table. The fields name should not be python
reserve words like clean, save or delete etc.

Django provides various built-in fields types.

Field Name Class Particular

AutoField class AutoField(**options) It An IntegerField that automatically


increments.

BigAutoField class BigAutoField(**options) It is a 64-bit integer, much like an AutoField


except that it is guaranteed to fit numbers
from 1 to 9223372036854775807.

BigIntegerField class BigIntegerField(**options) It is a 64-bit integer, much like an


IntegerField except that it is guaranteed to fit
numbers from -9223372036854775808 to
9223372036854775807.

BinaryField class BinaryField(**options) A field to store raw binary data.

BooleanField class BooleanField(**options) A true/false field. The default form widget for
this field is a CheckboxInput.

CharField class DateField(auto_now=False, It is a date, represented in Python by a


auto_now_add=False, **options) datetime.date instance.

DateTimeField class DateTimeField(auto_now=False, It is a date, represented in Python by a


auto_now_add=False, **options) datetime.date instance.

DateTimeField class DateTimeField(auto_now=False, It is used for date and time, represented in


auto_now_add=False, **options) Python by a datetime.datetime instance.

DecimalField class DecimalField(max_digits=None, It is a fixed-precision decimal number,


decimal_places=None, **options) represented in Python by a Decimal instance.

DurationField class DurationField(**options) A field for storing periods of time.

EmailField class EmailField(max_length=254, It is a CharField that checks that the value is a


**options) valid email address.

FileField class FileField(upload_to=None, It is a file-upload field.


max_length=100, **options)

FloatField class FloatField(**options) It is a floating-point number represented in


Python by a float instance.

ImageField class ImageField(upload_to=None, It inherits all attributes and methods from


height_field=None, width_field=None, FileField, but also validates that the uploaded
max_length=100, **options) object is a valid image.

IntegerField class IntegerField(**options) It is an integer field. Values from


-2147483648 to 2147483647 are safe in all
databases supported by Django.

NullBooleanField class NullBooleanField(**options) Like a BooleanField, but allows NULL as one of


the options.

PositiveIntegerFiel class PositiveIntegerField(**options) Like an IntegerField, but must be either


d positive or zero (0). Values from 0 to
2147483647 are safe in all databases
supported by Django.

SmallIntegerField class SmallIntegerField(**options) It is like an IntegerField, but only allows


values under a certain (database-dependent)
point.

TextField class TextField(**options) A large text field. The default form widget for
this field is a Textarea.

TimeField class TimeField(auto_now=False, A time, represented in Python by a


auto_now_add=False, **options) datetime.time instance.

Django Model Fields Example

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.

Common arguments available to all field types. All are optional.

Field Particulars
Options

Null Django will store empty values as NULL in the database.

Blank It is used to allowed field to be blank.

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.

Unique This field must be unique throughout the table.

Example:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

C. After creating the model it has to be activated for that we


need to perform migration by using the following command
$ python manage.py makemigrations <appname>

7. Introducing the Django Admin

a. Creating an admin user

First we’ll need to create a user who can login to the admin site. Run
the following command:

$ python manage.py createsuperuser

Enter your desired username and press enter.

Username: admin

You will then be prompted for your desired email address:

Email address: [email protected]

The fifinal step is to enter your password. You will be asked to enter
your password twice, the second time as a

confifirmation of the fifirst.

Password: **********

Password (again): *********

Superuser created successfully.

B. Now open admin site and enter the username and password
Localhost:8000/admin

C. Make the app modifiable in the admin

Only one more thing to do: we need to tell the admin that model objects have an admin interface. To do
this,

open the polls/admin.py file, and edit it to look like this:

polls/admin.py

from django.contrib import admin

from .models import Question

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).

9. Creating the Views for App


A. Open app folder/views.py and write the code as follows(example code )
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
B. To call the view, we need to map it to a URL - and for this we need a URLconf. To
create a URLconf in the app directory, create a file called urls.py.
//urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'), ]
C. The next step is to point the root URLconf at the apps.urls module. In
project/urls.py, add an import for django.urls.include and insert an include() in the
urlpatterns list, so you have:

//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.

Example: crating a view in polls/views.py

def index(request):

latest_question_list = Question.objects.order_by('-pub_date')[:3]

output = ', '.join([q.question_text for q in latest_question_list])

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.

10. Creating a Template for a VIEW:

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>

{% for question in latest_question_list %}

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

{% endfor %}

</ul>

{% else %}

<p>No polls are available.</p>

{% endif %}

</body>

</html>

D. Modify the view code:(example polls/views.py)

from django.http import HttpResponse

from django.template import loader# use to load the template file

from .models import Question

# Create your views here.

def index(request):

latest_question_list = Question.objects.order_by('-pub_date')[:3]

template = loader.get_template('polls/index.html')

context = { 'latest_question_list': latest_question_list,}

return HttpResponse(template.render(context, request))

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:

from django.shortcuts import render


from .models import Question

def index(request):

latest_question_list = Question.objects.order_by('-pub_date')[:5]

context = {'latest_question_list': latest_question_list}

return render(request, 'polls/index.html', context)

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.

E. Raising a 404 error

1. Import Http404 from

From django.http import Htrp404

2. Raise the exception on 404

Exxample:

def detail(request,question_id):

try:

question = Question.objects.get(pk=question_id)

except Question.DoesNotExist:

raise Http404("Question does not exist")

return render(request, 'polls/detail.html', {'question': question})

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.

Support for template engines


Confifiguration
Templates engines are configured with the TEMPLATES setting. It’s a list of configurations, one for each
engine. The default value is empty. The settings.py generated by the startproject command defines a more
useful value:

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.

You might also like