- Install Python in the system.
- Make a local folder in the disk (e.g., Django).
- Open the folder in the command prompt by typing
cmdin the address bar. - Install virtual environment in the folder:
pip install virtualenv
- Create a virtual environment folder:
virtualenv env
- Activate the virtual environment by navigating to scripts:
cd env cd scripts activate
- Navigate back to the main folder:
cd .. - Install Django in the virtual environment:
pip install Django
- Check if Django is successfully installed:
To exit, press
python import django django.__version__
ctrl + Z.
- Create a new Django project:
django-admin startproject core . - Navigate to the project folder:
cd core - Open VS Code to view the project:
code .
- Create a new app:
python manage.py startapp home
- Run the development server:
To exit the server, press
python manage.py runserver
CTRL + C. - Run the server on a custom port:
python manage.py runserver 0.0.0.0:5000
Note: Always add apps in the main directory in the settings.py in the "INSTALLED_APPS".
- Open the
views.pyin the app created to add the attributes. - Import HttpResponse:
from django.http import HttpResponse
- Create functions to add HTML content:
def home(request): return HttpResponse("<h1>Hey, this is a Django server</h1>")
- In the main directory, open the
urls.pyto add the path of the view just created. - Import the views from the app:
from home.views import *
- Add the path of the function:
urlpatterns = [ path('', home, name="home"), path('success_page/', success_page, name="success_page"), ]
- Create a templates folder in the app folder (e.g., core/home/templates).
- Create
index.htmlin the templates folder. - Create a render function for the
index.html:def home(request): return render(request, "index.html")
- Create a list of dictionaries in the
views.py:peoples = [ {'name': 'Rahul Prasad', 'age': 21}, {'name': 'Rahul Prasad', 'age': 21}, {'name': 'Rahul Prasad', 'age': 21} ]
- Declare the list in the return render:
return render(request, "home/index.html", context={'people': peoples})
- Display the data in the
index.html:<table> <tr> <th>S.no</th> <th>Name</th> <th>Age</th> </tr> {% for people in peoples %} <tr> <td>{{ forloop.counter }}</td> <td>{{ people.name }}</td> <td>{{ people.age }}</td> </tr> {% endfor %} </table>
<table>
<tr>
<th>S.no</th>
<th>Name</th>
<th>Age</th>
<th>Can vote</th>
</tr>
{% for people in peoples %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ people.name }}</td>
<td>{{ people.age }}</td>
<td {% if people.age >= 18 %} style="background:green;color:white;" {% else %} style="background:red;color:white;" {% endif %}>
{% if people.age >= 18 %}
👍
{% else %}
👎
{% endif %}
</td>
</tr>
{% endfor %}
</table>Create a text string in the views.py:
text = """Rahul embodies a rare blend of resilience and empathy that leaves a lasting impression on everyone he meets.
His unwavering determination and tireless work ethic are matched only by his genuine kindness and compassion towards others."""- Calling the text in the index.html
{{text}}- Truncatechars: filter truncate the value if it is longer than the specified number of characters
{{ text|truncatechars:80}}-
Working on the data and using it:
a. Create a list in the views.py
Vegetables =[ "pumpkin","tomato","potato"]
b. Add the new list to retrn render
return render(request,"home/index.html",context={'people' : peoples,'vegetables':vegetables})
c. Use the data in the index.html for data usage:
<p> {% if "cucumber" in vegetables %} yes avaiable {% elif "tomato" in vegetables %} yes avaiable {% endid %} </p>
- Create different html files in the templates.
'''sh
eg. about.html , contact.html
- Add diferent functions to the views.py for thr newly created html files.
def about(request): return render(request, "about.html") def contact(request): return render(request, "contact.html")
- Add the new functions in the urls to integrate them together in the urls.py of urlpatterns.
urlspatterns =[ path('',home,name="home"), path('about/',about,name="about"), path('contact/',contact,name="contact"), ]
- Add the different pages to the html file.
<a href="/contact/"> contact | <a href="/About/"> About
- Do similarly to all the html to make them inter linked
-
Create a base.html to add all the comman attributes .
-
add the repeated attributes to the base.html
-
the part which you don't want ot repeat add the follwing part
{% block start %} {% endblock %} -
change the html files accordingly, write the unquie code in the block:
{% extends "base.html" %} {% block start %} //Write your code here {% endblock %}
- Add the context in each page attributes.
def about(request): context={'page':'About'} return render(request, "about.html",context) def contact(request): context={'page':'Contact'} return render(request, "contact.html",context)
- Return the new dunctions value in te return render.
return render(request,"home/index.html",context={'page':'context','people' : peoples})
- add the returned file to the base.html
<title>{{page}}</title>
*Models in Django are Python classes that define the structure and behavior of your data.
*Migrations are a way to propagate changes you make to your models (such as adding new fields or altering existing ones) into
your database schema.- Open the app[home,account,any other app] that we have created and naviagte to models.py
- Create a class and call the library model in the class.
class Student(models.Model):
- Within the class define various fileds as the attributes of the class created.
name = models.Charfiled(max_length=100) age = models.IntegerField() email = models.Emailfiled() address = models.TextField() image = models.ImageField() file = models.FilesFiled()
- Similarly we can create other classes in the models.py and add attributes in them.
class Result(models.Model): pass
NOTE: sg Django use DBSqlite we need to install it in our system to see the different schema we created in out DataBase.-
All the changes and the migration files are stored in the dependencies of the 0001_intial.py and similarlies in the other dependdencies as we go on making chances .
-
we can then make migration in the terminal and add them to the database.
python manage.py makemigrations
-
We can check all the models in the terminal and if they are working properly or not.
python manage.py migrate
python manage.py shell exit from home.models import * students=Students(name="rahul",age=22email="rahul.3057.12@gamil.com,address="ranchi") studenta. Save the changes and then call the Schema.
1. students.save student=Student.objects.create(name="rahul",age=22email="rahul.3057.12@gamil.com,address="ranchi") 1. Student.objects.all()[]
2. Student.objects.all()[0].name {return the data at the 0 interval}
3. Student.objects.all()[0].address- make a new file in the app
utils.py
- Import the models and create a function in the file
from .models import Student def run_this_function() print("function Started") print("function Started..") print("function Started....") time.sleep(3) print("Function Ended")
- In order to run any file in the Django server we cannot directly run the python module in the IDe, in our case we have to import thr function in th shell and then execute it.
from home.utlis import * ```
- Then give the function you want to run from that file.
run_this_function()
-
class Car(models.Model): car_name = models.CharField(max_length=500) speed = models.Integerfield(default=50)
- Create a new migration to add the new schema in the database
python manage.py makemigrate python manage.py migrate
- start the python shell to perform the CRUD operations
python manage.py shell
- Import the schema from models
from home.models import *
- Make the class objects aviable in the shell
car=Car() car.save() car
- method 1 to add values to the schema.
car=car(car_name="ford",speed=110) car.save() car
- method 2 to add values to the schema.
car,objects.create(car_name="toyota",speed=200) car
- method 3 to add values to the schema.
- craete a dictionary and pass it to the class
car_dict = {"car_name": "maruti" , "speed":90}
- add the dictonary to the class
car.objects.create(**car_dict)
- craete a dictionary and pass it to the class
- Create a new function in the models.py
def __str__(self) -> str: return self.car_speed
for car in cars:
print("the car {car.id} name is {car.car_name} with high speed of {car.speed}")- create a new model in the models.py
recipe_view_count = models.IntegerField(default=1)
- make migrations and migrate the new model to the database.
- open python shell in the powershell
- import the app in the shell to perform teh actions
```python
from recipes.models import *
- check number of views created in the app
recipes = Recipe.objects.all() recipes
- import random in the shell
- set random value to the views using the random library
```python
for rep in recipes:
rep.recipe_view_count = random.randint(10,100)
rep.save()
- see the views new random value.
recipes = Recipe.objects.all() recipes[0].recipe_view_count recipes[1].recipe_view_count
- to get sorted data we call order by
recipes = Recipe.objects.all().order_by('recipe_view_count')
- to get data in decesding order we just add a minus sign
vege = Receipe.objects.all().order_by('-recipe_view_count')
- we just mention the range of the records to be fetched.
recipes = Recipe.objects.all().order_by('-recipe_view_count')[0:2]
- to get a specific view count nmber data value
b. to get all teh views count above or below the range (gte , lte)
Recipe.objects.filter(recipe_view_count = 55)
Recipe.objects.filter(recipe_view_count_gte = 55) OR Recipe.objects.filter(recipe_view_count_lte = 55)
- create certain models in the models.py
class Department (models.Model): department models.CharField(max_length=100) def _str_(self) -> str: return self.department class Meta: ordering = ['department'] class Student ID (models.Model): student_id = models.CharField(max_length=100) def _str_(self) -> str: return self.student_id class Student (models.Model): department = models.ForeignKey(Department related_name="depart",on_delete=models.CASC student_id = models. OneToOneField (StudentID, related_name="studentid", on_delete-models student_name = models.CharField(max_length=100) student_email = models. EmailField(unique=True) student_age = models.IntegerField(default=18) student_address = models.TextField() def _str_(self) -> str: return self.student_name class Meta: ordering = ['student_name'] verbose_name = "student"
- how to create the user for admin panel.
python manage.py createsuperuser Username (Leave blank to use 'pc'): rahul Email address:rahul.3057.12@gmail.com Password: 123
- Add the models to the admin.py
from django.contrib import admin # Register your models here. from .models import * admin.site.register (Recipe) admin.site.register(StudentID) admin.site.register(Student) admin.site.register(Department)
- using the faker library
- make a directory named seed.py in the app
- import the faker in the seed.py in the directory and generate the data
from faker import Faker fake = Faker() import random from .models import * def seed_db(n=10) -> None: for in range(n): departments_objs = IDepartment.objects.all() random_index = random.randint(0, len (departments_objs)-1) student_id == f'STU-0{random.randint (100, 999)}' department = departments_objs [random_index] student_name fake.name() student_email = fake.email() student_age = random.randint(20, 30) student_address fake. address() student_id_obj = Student ID.objects.create(student_id = student_id) student_obj = Student.objects.create( department =department, student_id = student_id_obj, student_name = student_name, student_email =student_email, student_age =student_age, student_address =student_address, )
- Create fake data in the admin panel by the shell in powershell
python python manage.py shell from recipes.seed import * seed_db()m [Note: run this command as manay times as manay fake data you need to create]
- Go to the python shell
python manage.py shell
- import the models in the shell
from recipes.models import *
queryset = Students.objects.filter(students_name__startswith == "rah")
[note:using double underscores make it an operator in django]- printing the filtered data
querysetqueryset = Students.objects.filter(students_name__endswith == "sad")queryset = Students.objects.filter(students_email__endswith == ".org")
querysetfor q in queryset:
print(q.student_mail)- Use of icontains:
queryset = Student.objects.filter(student_name__icontains = "ra")
queryset
queryset[0].student_id
queryset[0].department- extracting the data from a particular views:
queryset Student.objects.filter(department__department = "Civil")
[ The double underscore denotes the use of the foriegn key]- use of teh icontains with the foriegn key :
queryset Student.objects.filter(department__department__icointains = "Civil")count the derived querysets :
queryset.count()- extracting the data using the list .
d = ['Civil', 'Electrical'. 'Computer Science' ]
queryset Student.objects.filter(department__department__in = d)
queryset.count()- using teh exclude keyword:
queryset Student.objects.exclude(department__department = "Civil")
queryset queryset = Student.objects.filter(student_name = "Rahul')
len(queryset)
[ note: if the set returned is zero than the data is not been retrieved ]queryset.exists()- works only for a single column .
- when we work on multiple columns .
from django.db.models import *
from recipes.models import *
Student.objects.aggregate(Avg('student_age')) from django.db.models import *
from recipes.models import *
Student.objects.aggregate(Max('student_age')) from django.db.models import *
from recipes.models import *
Student.objects.aggregate(Min('student_age')) from django.db.models import *
from recipes.models import *
Student.objects.aggregate(Sum('student_age')) from django.db.models import *
from recipes.models import *
Student.objects.values('student_age').annotate(Count('student_age'))