KEMBAR78
WADF LAB Experiments | PDF | Computer File | System Software
0% found this document useful (0 votes)
10 views48 pages

WADF LAB Experiments

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views48 pages

WADF LAB Experiments

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

1.

File Structure of Angular JS

Workspace and project file structure


You develop applications in the context of an Angular workspace. A workspace contains the files for one
or more projects. A project is the set of files that comprise a standalone application or a shareable library.
The Angular CLI ng new command creates a workspace.
ng new <my-project>

Application project files

By default, the CLI command ng new my-app creates a workspace folder named "my-app" and generates
a new application skeleton in a src/ folder at the top level of the workspace. A newly generated application
contains source files for a root module, with a root component and template.

Application source files

Files at the top level of src/ support testing and running your application. Subfolders contain the
application source and application-specific configuration.

APPLICATION
PURPOSE
SUPPORT FILES

Contains the component files in which your application


APP/ logic and data are defined. See details below.

Contains image and other asset files to be copied as-is when


assets/ you build your application.
favicon.ico An icon to use for this application in the bookmark bar.

The main HTML page that is served when someone visits


your site. The CLI automatically adds all JavaScript and
CSS files when building your app, so you typically don't
index.html need to add any <script> or <link> tags here manually.

The main entry point for your application. Compiles the


application with the JIT compiler and bootstraps the
application's root module (AppModule) to run in the
browser. You can also use the AOT compiler without
changing any code by appending the --aot flag to the
main.ts CLI build and serve commands.

Lists CSS files that supply styles for a project. The


extension reflects the style preprocessor you have
styles.css configured for the project.

Inside the src folder, the app folder contains your project's logic and data. Angular components, templates,
and styles go here.
SRC/APP/ FILES PURPOSE

Defines the application config logic that tells Angular


how to assemble the application. As you add more
app/app.config.ts providers to the app, they must be declared here.

Defines the logic for the application's root component,


named AppComponent. The view associated with this
root component becomes the root of the view
hierarchy as you add components and services to your
app/app.component.ts application.

Defines the HTML template associated with the


app/app.component.html root AppComponent.

Defines the base CSS stylesheet for the


app/app.component.css root AppComponent.

app/app.component.spec.ts Defines a unit test for the root AppComponent.

Defines the root module, named AppModule, that tells


Angular how to assemble the application. Initially
declares only the AppComponent. As you add more
app/app.module.ts components to the app, they must be declared here.
This file is not generated when using --no-
standalone option.

2.Implementation of angular components

Angular components overview


Components are the main building blocks for Angular applications. Each component consists of:

 An HTML template that declares what renders on the page


 A TypeScript class that defines behavior
 A CSS selector that defines how the component is used in a template
 Optionally, CSS styles applied to the template

Creating a component
The best way to create a component is with the Angular CLI. You can also create a component manually.

Creating a component using the Angular CLI

To create a component using the Angular CLI:

From a terminal window, navigate to the directory containing your application.


Run the ng generate component <component-name> command, where <component-name> is the name
of your new component.

By default, this command creates the following:

A directory named after the component


A component file, <component-name>.component.ts

A template file, <component-name>.component.html


A CSS file, <component-name>.component.css
A testing specification file, <component-name>.component.spec.ts
Where <component-name> is the name of your component.

Creating a component manually

Although the Angular CLI is the best way to create an Angular component, you can also create a
component manually. This section describes how to create the core component file within an existing
Angular project.

To create a new component manually:

Navigate to your Angular project directory.

Create a new file, <component-name>.component.ts.

At the top of the file, add the following import statement.

import { Component } from '@angular/core';

After the import statement, add a @Component decorator.

@Component({
})

Choose a CSS selector for the component.


@Component({

selector: 'app-component-overview',
})

Define the HTML template that the component uses to display information. In most cases, this template
is a separate HTML file.

@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})

Select the styles for the component's template. In most cases, you define the styles for your component's
template in a separate file.

@Component({

selector: 'app-component-overview',
templateUrl: './component-overview.component.html',

styleUrls: ['./component-overview.component.css']
})

Add a class statement that includes the code for the component.

export class ComponentOverviewComponent {

Defining a component's template


A template is a block of HTML that tells Angular how to render the component in your application. Define
a template for your component in one of two ways: by referencing an external file, or directly within the
component.

To define a template as an external file, add a templateUrl property to the @Component decorator.

@Component({

selector: 'app-component-overview',
templateUrl: './component-overview.component.html',

})
To define a template within the component, add a template property to the @Component decorator that
contains the HTML you want to use.

@Component({
selector: 'app-component-overview',

template: '<h1>Hello World!</h1>',


})

If you want your template to span multiple lines, use backticks (`). For example:

@Component({

selector: 'app-component-overview',
template: `

<h1>Hello World!</h1>
<p>This template definition spans multiple lines.</p>
`

})

3.Implementation of custom/user-defined directive

Creating an Attribute Directive


1. Generate the Directive:

o To create an attribute directive, use the Angular CLI command ng generate directive
<directive-name>.
o For instance, if you want to create a directive called “highlight,” run:
 ng generate directive highlight
o This generates the directive file (highlight.directive.ts) and a corresponding test file
(highlight.directive.spec.ts).

2. Define the Directive Class:

 Open the generated highlight.directive.ts file.


 Import ElementRef from @angular/core.
 Annotate the class with the @Directive decorator, specifying the CSS attribute selector
(e.g., [appHighlight]).
 Inject ElementRef into the directive’s constructor to access the host DOM element.
 Add logic to modify the element (e.g., set its background color to yellow).

3. Example: Highlight Directive:

 Let’s create a simple directive that highlights an element by changing its background
color to yellow when the user hovers over it.
 Here’s the code for the highlight.directive.ts:

TypeScript

highlight.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private el: ElementRef) {}

@HostListener('mouseenter')
onMouseEnter() {
this.highlight('yellow');
}

@HostListener('mouseleave')
onMouseLeave() {
this.highlight('');
}

private highlight(color: string) {


this.el.nativeElement.style.backgroundColor = color;
}
}
4. Using the Directive:

 In your component’s HTML template, apply the appHighlight directive to an element


(e.g., a <p> tag).
 Angular will create an instance of the HighlightDirective class and inject a reference
to the element.
 When the user hovers over the element, the background color will change to yellow.
5. Example Usage:

HTML

<!-- app.component.html -->


<p appHighlight>Hover over me!</p>
Experiment 5
Develop a simple To-Do applica on using Angular.js

Todolist.component.html

<div class="container">

<h1>To-Do Applica on</h1>

<hr>

<form (ngSubmit)="onSubmit(taskForm)" #taskForm="ngForm">

<div class="form-group">

<label for="task">Task</label>

<input type="text" class="form-control" id="task" placeholder="Enter task"

ngModel name="task" required>

<small *ngIf="taskForm.invalid && taskForm.dirty" id="errorMessage"

class="form-text text-danger">Required

field</small>

</div>

<bu on [disabled]="taskForm.invalid" id="submitBu on" type="submit" class="btn

btn-primary">Submit</bu on>

</form>

<hr>

<table class="table">

<thead>

<tr>

<th scope="col">Task</th>

<th scope="col">Completed</th>

<th scope="col">Delete</th>
</tr>

</thead>

<tbody>

<tr *ngFor="let t of taskArray; index as i">

<td>{{t.taskName}}</td>

<td><input (change)="onCheck(i)" id="myCheckbox" type="checkbox"></td>

<td><bu on class="btn btn-danger btn-sm"

(click)="onDelete(i)">Delete</bu on></td>

</tr>

</tbody>

</table>

</div>

Todolist.component.ts

import { Component, OnInit } from '@angular/core';

import { NgForm } from '@angular/forms';

@Component({

selector: 'app-todolist',

templateUrl: './todolist.component.html',

styleUrls: ['./todolist.component.css']

})

export class TodolistComponent implements OnInit {

taskArray = [{ taskName: 'Brush teeth', isCompleted: false }];

constructor() { }
ngOnInit(): void {

onSubmit(form: NgForm) {

console.log(form);

this.taskArray.push({

taskName: form.controls['task'].value,

isCompleted: false

})

form.reset();

onDelete(index: number) {

console.log(index);

this.taskArray.splice(index, 1);

onCheck(index: number) {

console.log(this.taskArray);

this.taskArray[index].isCompleted = !this.taskArray[index].isCompleted;

}
5.Implement routing and navigation in Angular JS
How to implement routing and navigation in an Angular application without using modules.

1.Create an Angular Application: First, create a new Angular project using the following command:

ng new angular-routing-without-modules
2.Create Components: Generate components for different views/pages within your app:

ng generate component home

ng generate component about

ng generate component contact


3.Configure Routes: Open the app-routing.module.ts file (create it if it doesn’t exist) and
define your routes

import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';

import { AboutComponent } from './about/about.component';

import { ContactComponent } from './contact/contact.component';

const routes: Routes = [

{ path: '', redirectTo: '/home', pathMatch: 'full' },

{ path: 'home', component: HomeComponent },

{ path: 'about', component: AboutComponent },

{ path: 'contact', component: ContactComponent },

];

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule],

})

export class AppRoutingModule {}

4.Create Navigation Links: In your app.component.html, add navigation links to your views
<nav>

<a routerLink="/home">Home</a>

<a routerLink="/about">About</a>

<a routerLink="/contact">Contact</a>

</nav>

<router-outlet></router-outlet>

5.Display Views: Create the corresponding templates for your components


(home.component.html, about.component.html, and contact.component.html). For
example:

<!-- home.component.html -->

<h1>Welcome to the Home Page!</h1>

<!-- about.component.html -->

<h1>About Us</h1>

<p>We are a passionate team...</p>

<!-- contact.component.html -->

<h1>Contact Us</h1>

<p>Feel free to reach out...</p>


6.Run Your App: Start your app using:

ng serve

Visit http://localhost:4200 in your browser, and you’ll see your navigation links. Clicking on
them will load the corresponding views.
REACT JS
Experiment : 1.React Components
Components:
React components are piece of code which we can use many times at any where in the
project.
There are two types of react components:
1.class components
2.function components
Class components:
Class components are constructed by extending React.Component
Ex:
import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
render()
{
return(<h1>hello world</h1>);
}
}
ReactDOM.render(<Component1 />,document.getElementById('root'));

Using props in react class components:


import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
render()
{
return(<h1>hello world {this.props.name}</h1>);
}
}
ReactDOM.render(<Component1 name="red" />,document.getElementById('root'));
Using of state in react class component:
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './components/first';
class Component1 extends React.Component{
state={
name:"red"
}
render()
{
return(<h1>hello world {this.props.name}</h1>);
}
}
ReactDOM.render(<Component1 name="red" />,document.getElementById('root'));
We can use setState inbuit function to modify the state variable dynamically.
Function templates:
import React from 'react';
import ReactDOM from 'react-dom';
function Template1(){
return <h2>hi ! </h2>;
}
ReactDOM.render(<Template1 />, document.getElementById('root'));
Using props in function template:
import React from 'react';
import ReactDOM from 'react-dom';
function Template1(props){
return <h2>hi! {props.name}</h2>;
}
ReactDOM.render(<Template1 name="nani"/>, document.getElementById('root'));

Experiment : 2. React router and singe page web application :


Initially react does not contain any routing functionalities.
To incorporate the routing functionalities we have to install the command in our project
npm i -D react-router-dom@latest
index.js:
import ReactDOM from "react-dom";
import { BrowserRouter, Routes, Route } from "react-router-dom";

import Home from "./pages/Home";


import Blogs from "./pages/Blog";
import Layout from "./pages/Layout";
import NoPage from "./pages/NoPage";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="blogs" element={<Blogs />} />
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
);
}

ReactDOM.render(<App />, document.getElementById("root"));


Layout.js
import { Outlet, Link } from "react-router-dom";
const Layout = () => {
return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/blogs">Blogs</Link>
</li>
</ul>
</nav>
<Outlet />
</>
)
};
export default Layout;
Home.js:
const Home = () => {
return <h1>Home</h1>;
};
export default Home;
Blogs.js:
const Blogs = () => {
return <h1>Blog Articles</h1>;
};
export default Blogs;
NoPage.js:
const NoPage = () => {
return <h1>404</h1>;
};
export default NoPage;

Experiment 3: Controlled Form Validation, Uncontrolled forms


Controlled Form Validation: Controlled Components
import React, { useState } from 'react';
const MyForm = () => {
// State to hold form data
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});
// Handler for form input changes
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
// Handler for form submission
const handleSubmit = (e) => {
e.preventDefault();
// Do something with formData, like sending it to a server
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
placeholder="Username"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
placeholder="Password"
/>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
Uncontrolled forms: Uncontrolled Components
import React, { useRef } from 'react'
const MyForm = () => {
// Refs to hold input values
const usernameRef = useRef(null);
const emailRef = useRef(null);
const passwordRef = useRef(null);
// Handler for form submission
const handleSubmit = (e) => {
e.preventDefault();
// Access input values using refs
const formData = {
username: usernameRef.current.value,
email: emailRef.current.value,
password: passwordRef.current.value
};
// Do something with formData, like sending it to a server
console.log(formData);
// Optionally, clear form fields
usernameRef.current.value = '';
emailRef.current.value = '';
passwordRef.current.value = '';
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
ref={usernameRef}
placeholder="Username"
/>
<input
type="email"
ref={emailRef}
placeholder="Email"
/>
<input
type="password"
ref={passwordRef}
placeholder="Password"
/>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;

Experiment 4: Create a TODO Application using React JS


import React, { useState } from 'react';
function TodoApp() {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');

const handleInputChange = (event) => {


setInputValue(event.target.value);
};
const handleAddTodo = () => {
if (inputValue.trim() !== '') {
setTodos([...todos, inputValue]);
setInputValue('');
}
};
const handleDeleteTodo = (index) => {
const updatedTodos = [...todos];
updatedTodos.splice(index, 1);
setTodos(updatedTodos);
};
return (
<div>
<h1>TODO List</h1>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter a new TODO"
/>
<button onClick={handleAddTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => handleDeleteTodo(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default TodoApp;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoApp from './TodoApp';
ReactDOM.render(
<React.StrictMode>
<TodoApp />
</React.StrictMode>,
document.getElementById('root')
);

Experiment 5: Creating a movie list Application in React JS


App.js
function App() {
return (
<div>
<h1>Movie List Application</h1>
<MovieList />
</div>
);
}
export default App;
MovieList.js
import React, { useState, useEffect } from 'react';
import MovieItem from './MovieItem';
const MovieList = () => {
const [movies, setMovies] = useState([]);
useEffect(() => {
fetchMovies();
}, []);

const fetchMovies = async () => {


try {
const response = await fetch(

'https://api.themoviedb.org/3/search/movie?api_key=fb5be735705694186dd43ba8fe1
9143f&query=The%20Marvels'
);
const data = await response.json();
setMovies(data.results);
} catch (error) {
console.error('Error fetching movies:', error);
}
};
return (
<div>
<h2>Movie List</h2>
<ul>
{movies.map(movie => (
<MovieItem key={movie.id} movie={movie} />
))}
</ul>
</div>
);
};
export default MovieList;

MovieItem.js
import React from 'react';
const MovieItem = ({ movie }) => {
return (
<li>
<img
src={`https://image.tmdb.org/t/p/w200/${movie.poster_path}`}
alt={movie.title}
/>
<h3>{movie.title}</h3>
<p>{movie.release_date}</p>
</li>
);
};

export default MovieItem;

Experiment 6: Creating a Progressive web application with Reusable React


Components
Creating a Progressive Web Application (PWA) with reusable React components involves
structuring your application to be modular and scalable. Here's a basic example of how you
can create a PWA with reusable React components:
Setup your React environment: You can use tools like Create React App to quickly set up a
new React project with PWA support. Run the following commands in your terminal:

npx create-react-app my-pwa-app


cd my-pwa-app

Install additional dependencies: You'll need some additional dependencies for building a
PWA. Install them using npm or yarn:

npm install --save react-router-dom react-icons


Create reusable components: Create individual components for different parts of your
application. For example, you might have components for a header, navigation, footer, etc.
Here's an example of a reusable component for a header:
// Header.js
import React from 'react';

function Header() {
return (
<header>
<h1>My PWA App</h1>
</header>
);
}
export default Header;

Create your main application: Use these reusable components to build your main
application. Here's an example of how you might structure your main application using React
Router for navigation:

// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Header from './Header';
import Home from './Home';
import About from './About';

function App() {
return (
<Router>
<div>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
</Router>
);
}
export default App;

Define your routes: Create separate components for each route of your application. For
example:

// Home.js
import React from 'react';
function Home() {
return (
<div>
<h2>Welcome to the Home page!</h2>
</div>
);
}
export default Home;
// About.js
import React from 'react';
function About() {
return (
<div>
<h2>About Us</h2>
<p>This is the about page of our application.</p>
</div>
);
}
export default About;

Make your app a PWA: To turn your React app into a PWA, you need to add a manifest file
(manifest.json) and a service worker (service-worker.js). You can use tools like create-react-
app to generate these files automatically, or you can create them manually.
Test your PWA: Once everything is set up, test your PWA in a browser that supports service
workers. You should be able to see your app load even when offline, thanks to the service
worker caching.
Django

How to install Django and Create new App?

Django is a high-level Python framework designed for rapid, secure, and scalable web development. Django
includes rich support for URL routing, page templates, and working with data.

Installation of Django
Create a project environment for the Django Tutorial
In this section, you create a virtual environment in which Django is installed. Using a virtual environment
avoids installing Django into a global Python environment and gives you exact control over the libraries
used in an application. A virtual environment also makes it easy to Create a requirements.txt file for the
environment.
On your file system, create a project folder for this tutorial, such as hello_django.
In that folder, use the following command (as appropriate to your computer) to create a virtual environment
named .venv based on your current interpreter:
# Windows
py -3 -m venv .venv
.venv\scripts\activate
Open the project folder in VS Code by running code ., or by running VS Code and using the File > Open
Folder command.
In VS Code, open the Command Palette (View > Command Palette or (Ctrl+Shift+P)). Then select the
Python: Select Interpreter command:

The command presents a list of available interpreters that VS Code can locate automatically (your list will
vary; if you don't see the desired interpreter, see Configuring Python environments). From the list, select the
virtual environment in your project folder that starts with ./.venv or .\.venv:
Run Terminal: Create New Terminal (Ctrl+Shift+`) from the Command Palette, which creates a terminal and
automatically activates the virtual environment by running its activation script.
The selected environment appears on the right side of the VS Code status bar, and notices the ('.venv': venv)
indicator that tells you that you're using a virtual environment:

Update pip in the virtual environment by running the following command in the VS Code Terminal:

python -m pip install --upgrade pip

Install Django in the virtual environment by running the following command in the VS Code
Terminal:
python -m pip install Django

Create the Django project


In the VS Code Terminal where your virtual environment is activated, run the following command:

django-admin startproject web_project

This startproject command assumes (by use of . at the end) that the current folder is your project
folder, and creates the following within it:

manage.py: The Django command-line administrative utility for the project. You run administrative
commands for the project using python manage.py <command> [options].

A subfolder named web_project, which contains the following files:

__init__.py: an empty file that tells Python that this folder is a Python package.
asgi.py: an entry point for ASGI-compatible web servers to serve your project. You typically leave
this file as-is as it provides the hooks for production web servers.
settings.py: contains settings for Django project, which you modify in the course of developing a web
app.
urls.py: contains a table of contents for the Django project, which you also modify in the course of
development.
wsgi.py: an entry point for WSGI-compatible web servers to serve your project. You typically leave
this file as-is as it provides the hooks for production web servers.

Create an empty development database by running the following command

python manage.py migrate

When you run the server the first time, it creates a default SQLite database in the file db.sqlite3 that is
intended for development purposes, but can be used in production for low-volume web apps.
o verify the Django project, make sure your virtual environment is activated, then start Django's
development server using the command python manage.py runserver. The server runs on the default
port 8000, and you see output like the following output in the terminal window:

Django's built-in web server is intended only for local development purposes. When you deploy to a
web host, however, Django uses the host's web server instead. The wsgi.py and asgi.py modules in the
Django project take care of hooking into the production servers.

If you want to use a different port than the default 8000, specify the port number on the command line,
such as python manage.py runserver 5000.

Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open your default browser
to that address. If Django is installed correctly and the project is valid, you see the default page shown
below. The VS Code terminal output window also shows the server log.
When you're done, close the browser window and stop the server in VS Code using Ctrl+C as
indicated in the terminal output window

Django-admin is used to create Django project. It provide basic initial setup and It configure and
database.

django-admin startproject mysite


This will create mysite directory in your current directory. And we can create apps in the project. This
is can be assumed as parent or base. Mysite is our project manage.py is file which does all heavy lifting
in the Django project. Settings.py is file in which we configure database and Installed apps. In this file
we will configure all for Django project. Urls.py which urls are configured. asgi.py, wsgi.py files are
used as entry point for ASGI-compatible web servers, WSGI-compatible web server.

Project structure after creating project.

mysite/ manage.py

mysite/

init .py settings.py

urls.py asgi.py

wsgi.py

Check the installation by starting the server python mange.py runserver

Starting App in Django

We are creating app called polls and we will do all work in polls apps itself

python manage.py startapp polls

App project structure polls/

init .py admin.py

apps.py migrations/

init .py models.py

tests.py views.py
Let’s Write first Basic view

Polls/views.py

from Django.http import HttpResponse

def index(request):

return HttpResposne(“Hello, World. You’re at polls index”)

We had created view right, we also need urls.py file as url routing should be like
some.com/polls/ this search for polls app to urls file to index function.

Create a new file in the polls folder with name of urls.py

Polls/urls.py

from django.urls import path

from . import views

urlpatterns = [

path('', views.index, name='index'),

After creating we need to configure our project urls. Go to mysite folder which will be in mysite folder.
And open urls.py file

mysite/urls.py

from django.contrib import admin from

django.urls import include, path

urlpatterns = [

path('polls/', include('polls.urls')),

path('admin/', admin.site.urls),

Let’s start our project using python manage.py runserver

You will be get like this.


We get this as had not configured base url for “/” we can do it later now add /polls/ to the url.

You will get Hello world….. text from the index function from polls view file And congrats we had
created basic view we can as many views in polls view with same syntax.

Q. Create models for database queries?


Note:
If experiment ask only for models and write about it write from here to Admin panel. If experiment ask
to create a project and execute and show entire working then make sure you I have minimum idea about
installation and views.
Creating models
polls/model.py
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200) pub_date
= models.DateTimeField('date published')

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

Here, each model is represented by a class that subclasses django.db.models.Model. Each model has
a number of class variables, each of which represents a database field in the model.

Each field is represented by an instance of a Field class – e.g., CharField for character
felds and DateTimeField for datetimes. This tells Django what type of data each field
holds.

To activate we need to first add our polls INSTALLED_APPS which is in the settings.py file in mysite file.

Add this line to INSTALLED_APPS list 'polls.apps.PollsConfig' after adding

mysite/settings.py INSTALLED_APPS =

'polls.apps.PollsConfig',

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',
'django.contrib.staticfiles',

To save the changes to database we need to migrate.

python manage.py makemigrations polls

It will show all changes that are made in the models.py file, We had created new model
Question, Choice so, It shows as Created.

Now migrate the it using

python manage.py sqlmigrate polls 0001

Now let’s migrate everything using


python manage.py migrate
Without executing this we cannot create user make user you don’t skip this step. We can view the
our models in Admin panel

Admin Panel
Creating the Super user
Using this we will be creating super user

python manage.py createsuperuser

This will ask few info make sure Username and Password. Username: Admin, Password: root
while typing password it will appear just type and go.
Now go to http://127.0.0.1:8000/admin it prompt login system

Now register the questions model in the polls/admin.py file


polls/admin.py

from django.contrib import admin

from .models import Question

admin.site.register(Question)

we are importing the Question from model and registering it Try the same for Choice just add Choice to
import and register with the same syntax. After saving you will get like this
Q. Writing Django templates for rendering data?
Note:
If they only for ask for template write about creating templates folder and file location
“polls/template/polls/index.html” polls view and view file. For templates we need urls.py, views.py,
template file.

Templates in Django?
We will be creating updating the project to show to questions and showing dynamic content based on
urls
Let’s Fist add few more views to polls/view.py folder.
Data rendering dynamically from view and also write index function which is in below the screenshot
Add this lines this is to the polls/view.py

from .models import Question

def index(request):

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

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


return HttpResponse(output)

def detail(request, question_id):


return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):


response = "You're looking at the results of question %s." return
HttpResponse(response % question_id)

def vote(request, question_id):


return HttpResponse("You're voting on question %s." % question_id)
Explanation:
Consider details view here we getting question_id as argument consider http://127.0.0.1:8000/polls/2/
this take 2 and show the output as your looking at question 2 same other views too. To work we need to
first update our urls file in polls app. It will not until you do changes in urls file. Explanation of index
is below down.
Let’s Update the Urls to support above operation

from django.urls import path

from . import views

urlpatterns = [
path('', views.index, name='index'),

path('<int:question_id>/', views.detail, name='detail'),

path('<int:question_id>/results/', views.results, name='results'),

path('<int:question_id>/vote/', views.vote, name='vote'),


]

Here taking number which passing in url as our question id and using it view file.
<int:question_id>
<datatype:variable_name name=”view name”>
Same for <int:question_id/results it will rendering results which question it.
Let’s Update Index view to Show all the data in database

from .models import Question

def index(request):

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

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

return HttpResponse(output)

Add these and replace the index view with this code.
Explanation:
We getting all latest question from using objects which is predefined in models and orderby date
created upto top 5.
Create new questions in Admin panel in case you had not created one
Now let’s create one template.
Django had predefined structure to create templates.
Create template file.
In polls folder create templates (currently we only specific to the polls app only). Create another folder
with name of app name we had polls so we will be create as polls and create new file index.html
polls/template/polls/index.html
{% 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 %}
Explanation:
We use {{ }} for variables. We use {% %} for writing tags it used to write more complex than
variables like logic and some conditionals. If latest_question_list is exist it wil return Boolean as true
we already know that if true it executes as printing all the question text
Output will be polls index and Dynamically showing Question_id, results.. Polls/
polls/2
Polls/2/results/
It can work with any number we just getting number from url and showing in the view

Experiment 3: Implementation of REST API using Django

Django REST Framework Django REST Framework is added just like any other third-party app. Make sure
to quit the local server Control+c if it is still running. Then on the command line type the below

(library) $ pip install djangorestframework==3.10.3

Add rest_framework to the INSTALLED_APPS config in our settings.py file. I like to make a distinction
between third-party apps and local apps as follows since the number of apps grows quickly in most projects.

# library_project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework', # new
]

Ultimately our API will expose a single endpoint that lists out all books in JSON. So we will need a new
URL route, a new view, and a new serializer file (more on this shortly). There are multiple ways we can
organize these files however my preferred approach is to create a dedicated api app. That way even if we add
more apps in the future, each app can contain the models, views, templates, and urls needed for dedicated
webpages, but all API-specific files for the entire project will live in a dedicated api app. Let’s first create a
new api app.

(library) $ python manage.py startapp api

Then add it to INSTALLED_APPS.

# library_project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework',
# Local
'api.apps.ApiConfig', # new
]

The api app will not have its own database models so there is no need to create a migration file and update
the database as we normally would.

URLs Let’s start with our URL configs. Adding an API endpoint is just like configuring a traditional Django
app’s routes. First at the project-level we need to include the api app and configure its URL route, which will
be api/.

# library_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns
= [ path('admin/', admin.site.urls), path('', include('books.urls')), path('api/', include('api.urls')), # new ]

Then create a urls.py file within the api app.


# api/urls.py
from django.urls import path
from .views import BookAPIView
urlpatterns = [
path('', BookAPIView.as_view()),
]

Views Next up is our views.py file which relies on Django REST Framework’s built-in generic class views.
These deliberately mimic traditional Django’s generic class-based views in format, but they are not the same
thing. To avoid confusion, some developers will call an API views file apiviews.py or api.py. Personally,
when working within a dedicated api app I do not find it confusing to just call a Django REST Framework
views file views.py but opinion varies on this point. Within our views.py file, update it to look like the
following:

# api/views.py
from rest_framework import generics
from books.models import Book
from .serializers import BookSerializer
class BookAPIView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer

Serializers A serializer translates data into a format that is easy to consume over the internet, typically JSON,
and is displayed at an API endpoint. We will also cover serializers and JSON in more depth in following
chapters. For now I want to demonstrate how easy it is to create a serializer with Django REST Framework
to convert Django models to JSON

Make a serializers.py file within our api app.

# api/serializers.py
from rest_framework import serializers
from books.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'subtitle', 'author', 'isbn')

On the top lines we import Django REST Framework’s serializers class and the Book model from our books
app. We extend Django REST Framework’s ModelSerializer into a BookSerializer class that specifies our
database model Book and the database fields we wish to expose: title, subtitle, author, and isbn.

We want to see what our API endpoint looks like. We know it should return JSON at the URL
http://127.0.0.1:8000/api/. Let’s ensure that our local Django server is running:

(library) $ python manage.py runserver

Now open a new, second command line console. We will use it to access the API running in the existing
command line console. We can use the popular cURL program to execute HTTP requests via the command
line. All we need for a basic GET request it to specify curl and the URL we want to call.
$ curl http://127.0.0.1:8000/api/
[
{
"title":"Django for Beginners",
"subtitle":"Build websites with Python and Django",
"author":"William S. Vincent",
"isbn":"978-198317266"
}
]

The data is all there, in JSON format, but it is poorly formatted and hard to make sense of. Fortunately
Django REST Framework has a further surprise for us: a powerful visual mode for our API endpoints.

Browsable API With the local server still running in the first command line console, navigate to our API
endpoint in the web browser at http://127.0.0.1:8000/api/

You might also like