Django:
What is Django ?
Web Framework
Creates pre-existing codeCan be used to create mulitple apps like - blogs , authentication etc .,
Uses MVT architecture
MVT architecture (Model View Template)
No Controller unlike MVCBrowser > Django > urls.py > View
View pulls data from model(DB) and Displays it on Template (HTML)
How to use:
- No need to stop Django server when doing development
- There will be only 1 settings file in the main project to handle auths , templates etc.,
- When you want to create a new webpage do not modify the auto generated Framework.
- Always create your own app with the command ($python manage.py startapp app_name)
Example Source Code
Pre-Req:
- make sure python is installed.
- $pip install virtual env
- $virtualenv venv
- $source venv/bin/activate
- $pip install django
- If ur using Pycharm than goto : Preference>Select virtual Env created
Create django specific project , Create APP
- django-admin startproject Main #Start django project
- $cd Main
- python manage.py startapp PersonApp #Create App
- python manage.py runserver
- open http://127.0.0.1:8000/
- comment - settings.py > MIDDLEWARE >
Register APP:
- settings.py > Installed APP ['PersonApp']
- settings.py > TEMPLATES > 'DIRS': [os.path.join(BASE_DIR, 'PersonApp','html')] #import os
- Under urls.py
path('', include('PersonApp.urls'))
Steps:
1)PersonApp >html>person.html
<form method="POST"><p>{{ data }}</p>
<textarea name="fname">{{fname}}</textarea>
<textarea name="sname">{{sname}}</textarea>
<input type="submit">
</form>
2) #Under PersonApp/views.py
from django.shortcuts import renderdef person(request):
if request.method == "GET":
return render(request, 'person.html', {"data":"enter ur name"})
elif request.method == "POST":
fname = request.POST.get('fname', None)
sname= request.POST.get('sname', None)
print("accepted :"+fname)
return render(request, 'person.html', {"data":"Accepted !"})
3)#Under PersonApp/urls.py
from django.urls import path from . import views
urlpatterns= [path('',views.person,name='person')]
4) Create Model - #PersonApp/models.py
class Person(models.Model):first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
#Under admin.py
from .models import Personadmin.site.register(Person)
5) Create a DB from Model
python manage.py makemigrationspython manage.py migrate
python manage.py createsuperuser
0.0.0.0/admin
6) Adding and Retrieving Data fro Db
from .models import Persondef person():
person=Person()
person.first_name=fname
person.last_name=sname
person.save()
print("records ="+str(len(Person.objects.all())))
Ref for HTML looping and API:
URL Dispatching
- Copy a urls.py from base Framework into the new App folder
- Notice line "path('admin/', admin.site.urls)" in Framework urls.py eg: path is /admin than redirect to admin page
- Add below line in url.py in Base Framework
- This redirects "/test" to urls.py in the App folder.
- Add below lines in urls.py in app_name :
urlpatterns = [path('test', views.test,name="test")]
- In views.py of app_name add below lines:
def test(request):
return HttpResponse("Testpage")
- Notice here controls goes from url.py(base) >> url.py >> views.py
StaticFolders:
- The files inside static folders are made public
- Can Contain CSS / JS to be used in the webpage
- Create folder "static" inside project
- create file "test.txt" with some contents inside and save
- Add this to settings.py : STATICFILES_DIRS = [BASE_DIR / "static",'/var/www/static/',]
- open link -http://127.0.0.1:8000/static/test.txt
Create Templates with paramaters
- Create folder "templates" inside project
- Create a home.html inside templates with following :
- Goto settings.py > Under TEMPLATES > Add 'DIRS': [BASE_DIR / "templates",],
- Goto to the app views.py > Add line to the related resource method -
- BootStraping
- Used for ready made websites : https://getbootstrap.com/docs/4.5/getting-started/introduction/
- Copy Starter Template html
- You can use replace the html in home.html and save
- reload page
Template Inheritance
- Inherit the base template across the whole of the application
- Create base.html in templates folder
- Add templates html here , add placeholder for replacement wherever needed
- delete contents of home.html and add :
- In first line {% extends 'base.html' %}
- Add replacements for placeholder - {% block body %} HI {% endblock body %}
- Save
Using Images in Website:
Save any images into static folderRename the extension as ".jfif"
In the html file use as "/static/file.jfif"
Admin Logging Creation(We need to create Tables)
- $python manage.py createsuperuser
- Open http://127.0.0.1:8000/admin
To Create DB Table:
Model is a Table
Inside models.py
Eg:class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Register in admin.py :
from home.models import Person
admin.site.register(Person)
Register in Settings.py(under INSTALLED_APPS):
'home.apps.Person'
whenever u touch models.py , u need to run below commands
$python manage.py makemigrations #notice any changes and store in a DB.
$python manage.py migrate #Apply changes
API
1. Create a model
2. migrate it to create a DB
3. Create a serializer : Converts models to Json
4. Create a view and use the serializer
5. Create url.py and use the view
#https://www.youtube.com/watch?v=263xt_4mBNc
#https://www.youtube.com/watch?v=QB9gGEwxxM4
Pre-Req
- pip install djangorestframework
- settings.py > INSTALLED_APPS = 'rest_framework'
- url.py > urlpatterns=[path('api/', include('api.urls')),]
pip freeze > requirements.txt
python manage.py startapp api
create api/serializers.py : Converts models to Json
from .models import Person
class personSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Person
fields = ("url","first_name","last_name")
api/views.py
from .models import Person
from .serializers import personSerializer
#make sure Person model is created in models.py and migrated
class personView(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = personSerializer
create api/url.py : Handles all API endpoint
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('person',views.personview)
urlpatterns = [path('', include(router.urls))]
No comments:
Post a Comment