Django practical examples
Using the urls.py to display our content in views.py:
urls.py
from django.contrib import admin
from django.urls import path
from myApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path ('index/', views.index, name='index')
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('<h1>Hello index<h1>')
The above code in the django gives the following result
Create Tables using models.py
from django.db import models
# Create your models here.
class sampleTable(models.Model):
Row1 = models.CharField(max_length = 100)
Row2 = models.IntegerField()
For creating tables we use make migrations
in cmd type the following commands:
python manage.py makemigrations
python manage.py migrate
After the commands entered, empty sqlite3 file is filled with some table contents which was empty previously
opening python shell in cmd
python manage.py shell
>>> from myApp.models import sampleTable --> Imports the table
>>> sampleTable.objects.all() --> Displays the table created
Output:
<QuerySet []> --> Empty table without data
Adding objects to database
>>> a = sampleTable(row1 ="Raj", row2=25)
Saving the data
>>> a.save()
Output:
>>> from myApp.models import sampleTable
>>> sampleTable.objects.all()
<QuerySet [<sampleTable: Raj>]> --> Table with data
>>> exit()
Exited from the shell
Comments
Post a Comment