0% found this document useful (0 votes)
13 views

Module3 FS

Uploaded by

Spam Spam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Module3 FS

Uploaded by

Spam Spam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Rashtreeya Sikshana Samithi Trust

R V Institute of Technology and Management®


(Affiliated to VTU, Belagavi)

JP Nagar, Bengaluru - 560076

Department of Computer Science and Engineering

Course Name : FULL STACK DEVELOPMENT


Course Code : 21CS62

VI Semester - 2021 Scheme


MODULE-3
RV Institute of Technology and Management

Module-3
Django Admin Interfaces and Model Forms
The Django admin application can use your models to automatically build a site area that you
can use to create, view, update, and delete records. This can save a lot of time during
development, making it very easy to test your models and get a feel for whether you have
the right data. The admin application can also be useful for managing data in production,
depending on the type of website. The Django project recommends it only for internal data
management (i.e. just for use by admins, or people internal to your organization), as the model-
centric approach is not necessarily the best possible interface for all users, and exposes a lot of
unnecessary detail about the models.

Activating Django Admin Interface

The Django admin site is entirely optional, because only certain types of sites need this func

tionality. That means you’ll need to take a few steps to activate it in your project.

First, make a few changes to your settings file:

1. Add 'django.contrib.admin' to the INSTALLED_APPS setting. (The order of


INSTALLED_ APPS doesn’t matter, but we like to keep things alphabetical so it’s easy for a
human to read.)

2. Make sure INSTALLED_APPS contains 'django.contrib.auth', 'django.contrib.

contenttypes', and 'django.contrib.sessions'. The Django admin site requires

these three packages. (If you’re following along with our ongoing mysite project, note

that we commented out these three INSTALLED_APPS entries in Chapter 5. Uncomment

them now.)

3. Make sure MIDDLEWARE_CLASSES contains


'django.middleware.common.CommonMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware', and 'django.contrib.

auth.middleware.AuthenticationMiddleware'

Second, run python manage.py syncdb. This step will install the extra database tables

VI-Semester, CSE, Full Stack Development (21CS62) Page |1


RV Institute of Technology and Management

that the admin interface uses. The first time you run syncdb with 'django.contrib.auth' in

INSTALLED_APPS, you’ll be asked about creating a superuser. If you don’t do this, you’ll
need

to run python manage.py createsuperuser separately to create an admin user account; oth

erwise you won’t be able to log in to the admin site. (Potential gotcha: the python manage.py

createsuperuser command is available only if 'django.contrib.auth' is in your INSTALLED_

APPS.)

Third, add the admin site to your URLconf (in urls.py, remember). By default, the urls.py

generated by django-admin.py startproject contains commented-out code for the Django

admin, and all you have to do is uncomment it. For the record, here are the bits you need to

make sure are in there:

# Include these import statements...

from django.contrib import admin

admin.autodiscover()

# And include this URLpattern...

urlpatterns = patterns('',

# ...

(r'^admin/', include(admin.site.urls)),

# ...

Django Admin Interface

To start a project with Django it also provides a default admin interface that can be used to
perform create, read, update, and delete operations on the model directly. It reads a set of data
that explains and gives information about data from the model, to provide an instant interface
where the user can adjust the contents of the application. This is an in-built module designed
to execute admin-related work for the user.

VI-Semester, CSE, Full Stack Development (21CS62) Page |2


RV Institute of Technology and Management

Creating a Superuser in Django Project

The Superuser is the one who can access the Django administration panel and can perform
CURD operation on the created models which are shown in the admin panel. The admin
app(django.contrib.admin) is enabled by default and already added to the INSTALLED_APPS
list present in the settings.py file.

Fig 3.1 Installed Apps

To access this admin interface on browser write ‘/admin/’ at ‘localhost:8000/admin/’ and it


shows the output as given below:

Note: we are assuming that you have deployed your project on local server.

VI-Semester, CSE, Full Stack Development (21CS62) Page |3


RV Institute of Technology and Management

Fig 3.2 Admin Interface

It prompts for login details, if no login id is created before, then a new superuser can be created
by using the command given below:

python manage.py createsuperuser

Fig 3.3 Creating SuperUser

VI-Semester, CSE, Full Stack Development (21CS62) Page |4


RV Institute of Technology and Management

Now, access the admin login page after starting the Development Server which can be done by
using the command given below.

python manage.py runserver

Enter username and password, then hit login .

After logging in successfully, it shows the interface as shown below: .

Fig 3.4 Entering the User id and Password

Fig 3.5 Admin Dashboard

VI-Semester, CSE, Full Stack Development (21CS62) Page |5


RV Institute of Technology and Management

This is what is called a Django Admin Dashboard where one can add, delete and update data
belonging to any registered model.

Adding Your Models to the Admin Site

After starting your project in django and creating or resetting your django superuser you can
now access the django administrator and through django admin panel you can perform CRUD
operations on your models but the model you created in your app only shows in the admin
panel when you register them in your `admin.py` of the app you created.

python manage.py createapp myapp

Now in the myapp folder we have the file models.py in which we create our model and after
creating those model we need to register them in the admin.py file of the myapp folder after
that we make migrations of the model created.

Register model in django-admin

After model creation you have to register the model in django by registering them into admin.py
file of `myapp` folder.

First import your model at the top of the admin.py file if the model you are importing is in the
same file you can import by

from .models import <model.name>

Now we have to register the model in the admin.py file so that it can we visible on the admin
panel

admin.site.register<Model.name>.

The steps involved:

Register model in admin

Run the command python manage.py makemigrations

after that migrate all the migrations by the following command

pyhton manage.py migrate

VI-Semester, CSE, Full Stack Development (21CS62) Page |6


RV Institute of Technology and Management

Now the admin page will have the model Faculty_details but make sure the server is up and
running.

Fig 3.6 Admin Dashboard with the registered Models

Django Admin Interface

Django admin by default is highly responsive GUI, which offers various features and an overall
CRUD application to help developers and users. Moreover, Django admin can be customized
to fulfill one’s needs such as showing fields on the home page of the table, etc. In this

1.Changemodelname:
If you want to change name of model which is States here so open model.py file and add
verbose_name attribute in meta section.

state/model.py

class State(models.Model):
name = models.CharField(max_length = 50)
is_active = models.IntegerField(default = 1,
blank = True,
null = True,
help_text ='1->Active, 0->Inactive',
choices =(
(1, 'Active'), (0, 'Inactive')
))
created_on = models.DateTimeField(default = timezone.now)
updated_on = models.DateTimeField(default = timezone.now,

VI-Semester, CSE, Full Stack Development (21CS62) Page |7


RV Institute of Technology and Management

null = True,
blank = True
)
def __str__(self):
return self.name
class Meta:
db_table = 'state'
# Add verbose name
verbose_name = 'State List'

Output :

Fig 3.7 changing Model Name

2. By default django admin shows only object name in listing.

Fig 3.8 Default admin listing

One can show multiple fields data from model. Add some lines of code in your admin.py file.

state/admin.py:

VI-Semester, CSE, Full Stack Development (21CS62) Page |8


RV Institute of Technology and Management

from django.contrib import admin


from .models import State

class StateAdmin(admin.ModelAdmin):
list_display = ('name', 'active', 'created_on')

def active(self, obj):


return obj.is_active == 1

active.boolean = True

admin.site.register(State, StateAdmin)

Output :

E Fig 3.9 diting the dashboard

3. By default there is only one option which is delete option.


One can add more option on Action dropdown:

state/admin.py:

from django.contrib import admin


from django.contrib import messages
from .models import State

class StateAdmin(admin.ModelAdmin):
list_display = ('name', 'active', 'created_on')

def active(self, obj):


return obj.is_active == 1

active.boolean = True

VI-Semester, CSE, Full Stack Development (21CS62) Page |9


RV Institute of Technology and Management

def make_active(modeladmin, request, queryset):


queryset.update(is_active = 1)
messages.success(request, "Selected Record(s) Marked as Active Successfully !!")

def make_inactive(modeladmin, request, queryset):


queryset.update(is_active = 0)
messages.success(request, "Selected Record(s) Marked as Inactive Successfully !!")

admin.site.add_action(make_active, "Make Active")


admin.site.add_action(make_inactive, "Make Inactive")

admin.site.register(State, StateAdmin)

Output:

Fig 3.10 Deleting from the dashboard

4. Disable Delete option:

state/admin.py:

from django.contrib import admin


from django.contrib import messages
from .models import State

class StateAdmin(admin.ModelAdmin):
list_display = ('name', 'active', 'created_on')

def active(self, obj):


return obj.is_active == 1

active.boolean = True

def make_active(modeladmin, request, queryset):


queryset.update(is_active = 1)

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 10


RV Institute of Technology and Management

messages.success(request, "Selected Record(s) Marked as Active Successfully !!")

def make_inactive(modeladmin, request, queryset):


queryset.update(is_active = 0)
messages.success(request, "Selected Record(s) Marked as Inactive Successfully !!")

admin.site.add_action(make_active, "Make Active")


admin.site.add_action(make_inactive, "Make Inactive")

def has_delete_permission(self, request, obj = None):


return False

admin.site.register(State, StateAdmin)

Output:

Fig.3.11 Disabling delete option

5. Remove Add option:

state/admin.py:

from django.contrib import admin


from .models import State

class StateAdmin(admin.ModelAdmin):
list_display = ('name', 'active', 'created_on')

def active(self, obj):


return obj.is_active == 1

active.boolean = True

def has_add_permission(self, request):


return False

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 11


RV Institute of Technology and Management

admin.site.register(State, StateAdmin)

Fig 3.12 Removing the add option

Django Forms

Forms are used for taking input from the user in some manner and using that information for
logical operations on databases. For example, Registering a user by taking input such as his
name, email, password, etc.

Django maps the fields defined in Django forms into HTML input fields. Django handles three
distinct parts of the work involved in forms:

• Preparing and restructuring data to make it ready for rendering.

• Creating HTML forms for the data.

• Receiving and processing submitted forms and data from the client.

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 12


RV Institute of Technology and Management

Fig 3.13 Django Forms WorkFlow

Syntax : Django Fields work like Django Model Fields and have the syntax:

field_name = forms.FieldType(**options)

from django import forms

# creating a form
class RvitmForm(forms.Form):
title = forms.CharField()

Creating Forms in Django

Creating a form in Django is completely similar to creating a model, one needs to specify what
fields would exist in the form and of what type. For example, to input, a registration form one
might need First Name (CharField), Roll Number (IntegerField), and so on.

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 13


RV Institute of Technology and Management

Syntax:

from django import forms

class FormName(forms.Form):

# each field would be mapped as an input field in HTML

field_name = forms.Field(**options)

To create a form, in forms.py Enter the code

# import the standard Django Forms


# from built-in library
from django import forms

# creating a form
class InputForm(forms.Form):

first_name = forms.CharField(max_length = 200)


last_name = forms.CharField(max_length = 200)
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())

Render Django Forms

Django form fields have several built-in methods to ease the work of the developer but
sometimes one needs to implement things manually for customizing User Interface(UI). A form
comes with 3 in-built methods that can be used to render Django form fields.

• {{ form.as_table }} will render them as table cells wrapped in <tr> tags

• {{ form.as_p }} will render them wrapped in <p> tags

• {{ form.as_ul }} will render them wrapped in <li> tags

To render this form into a view, move to views.py and create a home_view as below

from django.shortcuts import render


from .forms import InputForm

# Create your views here.


def home_view(request):

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 14


RV Institute of Technology and Management

context ={}
context['form']= InputForm()
return render(request, "home.html", context)

In view, one needs to just create an instance of the form class created above in forms.py. Now
let’s edit templates > home.html

<form action = "" method = "post">


{% csrf_token %}
{{form }}
<input type="submit" value=Submit">
</form>

Now, visit http://localhost:8000/

Fig.3.14 Final output of the form

Create Django Form from Models

Django ModelForm is a class that is used to directly convert a model into a Django form. If
you’re building a database-driven app, chances are you’ll have forms that map closely to
Django models. Now when we have our project ready, create a model in Rvitm/models.py,

# import the standard Django Model


# from built-in library
from django.db import models

# declare a new model with a name "RvitmModel"


class RvitmModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
last_modified = models.DateTimeField(auto_now_add = True)

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 15


RV Institute of Technology and Management

img = models.ImageField(upload_to = "images/")

# renames the instances of the model


# with their title name
def __str__(self):
return self.title

URLConf Ticks

As a Django application grows in complexity, its URLconf grows, too, and keeping those
imports can be tedious to manage. (For each new view function, you have to remember to
import it, and the import statement tends to get overly long if you use this approach.) It’s
possible to avoid that tedium by importing the views module itself. This example URLconf
depicts that

from django.conf.urls.defaults import *


from mysite import views
urlpatterns = patterns('', (r'^hello/$', views.hello),
(r'^time/$', views.current_datetime),
(r'^time/plus/(d{1,2})/$', views.hours_ahead), )

Similarly we can write this as shown below


from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^hello/$', 'mysite.views.hello'),
(r'^time/$', 'mysite.views.current_datetime'),
(r'^time/plus/(d{1,2})/$', 'mysite.views.hours_ahead'),
)

A further shortcut you can take when using the string technique is to factor out a common
“view prefix.” In our URLconf example, each of the view strings starts with 'mysite.views',
which is redundant to type. We can factor out that common prefix and pass it as the first argu
ment to patterns(), like this

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 16


RV Institute of Technology and Management

from django.conf.urls.defaults import *


urlpatterns = patterns('mysite.views',
(r'^hello/$', 'hello'),
(r'^time/$', 'current_datetime'),
(r'^time/plus/(d{1,2})/$', 'hours_ahead'),
)

Using Multiple View Prefixes


In practice, if you use the string technique, you’ll probably end up mixing views to the point
where the views in your URLconf won’t have a common prefix. However, you can still take
advantage of the view prefix shortcut to remove duplication. Just add multiple patterns()
objects together, like this:
Old:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^hello/$', 'mysite.views.hello'),
(r'^time/$', 'mysite.views.current_datetime'),
(r'^time/plus/(\d{1,2})/$', 'mysite.views.hours_ahead'),
(r'^tag/(\w+)/$', 'weblog.views.tag'),
)
New:
from django.conf.urls.defaults import *
urlpatterns = patterns('mysite.views',
(r'^hello/$', 'hello'),
(r'^time/$', 'current_datetime'),
(r'^time/plus/(\d{1,2})/$', 'hours_ahead'),
)
urlpatterns += patterns('weblog.views',
(r'^tag/(\w+)/$', 'tag'),
)

VI-Semester, CSE, Full Stack Development (21CS62) P a g e | 17

You might also like