0% found this document useful (0 votes)
10 views19 pages

Django Imp

The document provides a comprehensive guide on creating and running a Django project, detailing the project structure, including key files like manage.py, settings.py, urls.py, views.py, and models.py. It explains the use of templates for presentation, how to define routes, and the process of creating models for database interaction, including handling relationships and forms. Additionally, it covers integrating Tailwind for styling and setting up an admin panel for managing the application.

Uploaded by

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

Django Imp

The document provides a comprehensive guide on creating and running a Django project, detailing the project structure, including key files like manage.py, settings.py, urls.py, views.py, and models.py. It explains the use of templates for presentation, how to define routes, and the process of creating models for database interaction, including handling relationships and forms. Additionally, it covers integrating Tailwind for styling and setting up an admin panel for managing the application.

Uploaded by

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

Django

Project creation:
First install the uv package as everything should be in a virtual environment.

Command :

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1


| iex"

Running Project
Project Structure:
Manage.py:
Entry Point for execution:
Settings.py:
Supports various settigs for project validation,middlewares etc:
For example:
urls.py
This is the file which is used mainly use for routing purpose
Admin is default route here but it is not configured by default :
After routing is done the next step is to determine what should be
displayed:
This setting is done in views.py(Not present initially)
Views.py:
Main business logic reside here

Models.py:
All database configurations reside here
In root folder make one templates folder for to show data in user-friendly
formats

Also make one static folder which contains all css,js files

Steps:
 First of all hit the url file
 Then control is shift to views.py
 Then we return simply return our file (for example : html)
 Database handling is done in models.py

Defining Routes:
After making view or routes go to url file
First of all import views

Handle routes:

Run project
For example view :
Templates in Django:
In Django, templates are used to separate the logic of the application (in views) from the
presentation (how the data is displayed on the web page).

While views handle fetching data and processing logic, templates are responsible for
displaying that data in a user-friendly format. By using templates, we can keep the code
clean, reusable, and easier to manage, especially when we need to change the design or layout
of a page without affecting the logic behind it.

In simple words, templates are like blueprints for the web pages. They define how the
information should be shown to the user, while views focus on the functionality and data
behind the scenes.

For rendering templates

Steps:

First of all in views.py import:

Next render your page:

But before rendering any thing in Django using templates first of all main
project should know where templates exists

For that redirect to settings.py:


After render view:

If your template exists in any other folder inside templates then don’t
forget to specify folder name of that template where it resides

Adding styling to files


Navigate to static folder that we have created earlier

But this will not work because it’s a normal code for injecting our program
code externally
We use template engines
{% static %}

But now also it wouldn’t work beause we have not given whole path
For that navigate to settings.py
For making apps in current project :

First of all in terminal run:

Above command will create new app


In settings.py add it

Write your codes


Then after definig views make urls.py in your new app
And just link it to sub links
Jinga Templates(Reusablity)

Yes, exactly! A Jinja template in Django (or any framework using


Jinja) is a reusable file that contains dynamic HTML content and
placeholders for data. It allows you to separate your Python logic
from the HTML presentation.
Else other process is same as we have followed earlier
For that we use Jinga templates
So basically we write block i.e, unnamed and name to write anything
daynamically
This is how it look like
How to use it after defining :

To connect our app with tailwind follow following process

Steps:
After this add your newly created app in settings.py
After this follow following steps:
TAILWIND_APP_NAME = ‘theme’
INTERNAL_IPS = [‘your ip’]
Now install your tailwind that is main process
Python manage.py tailwind install
But sometime it will perform installation process because in settings.py
NPM_BIN_PATH is not set
For that set it
NPM_BIN_PATH=r”your_path”
Also add your browser_reload in installed apps
You can find this path using where npm in cmd
Also add following command
'django_browser_reload.middleware.BrowserReloadMiddleware',

And also enable one path for auto reload in urls.py


path("__reload__/", include("django_browser_reload.urls")),

and also restart the project once again for reload support
Basic tailwind page

Now next is admin panel for accessing admin panel follow following
Steps
Models in Django
 Models are used in django for database interaction
Steps to write models :
 Navigate to models.py in your project structure
 First of all import models from djnago
i.e, from django.db import

Designing models
from django.db import models

from django.utils import timezone


class User(models.Model):
# handling enums
USER_TYPE = [
('admin','admin'),
('user','user'),
]
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/')
date_added = models.DateTimeField(default=timezone.now())
#definig enums
user_type = models.CharField(max_length=10, choices=USER_TYPE)

Note:
For handling images one short setting is needed in settings.py

i.e,

Also in urls.py add following :

Now everthing is ready


Apply migrations to save database migrations
Using following command
Python manage.py makemigrations
Python manage.py migrate

Now next is how to use this models :


from django.contrib import admin
from .models import User #importing the model , or any other model you
want to register
# Register your models here.
admin.site.register(User) #registering the model
Note:
define dunder string if you want
def __str__(self):
return f"Name: {self.name}, Email: {self.email}, Password:
{self.password}"

After you can see all the fields that are important at start

Now next is how to display this data on frontend


Steps:
1. Go to views.py
2. from django.shortcuts import render
3. from .models import User # import the model
4. # Create your views here.
5. def hi(request):
6. user = User.objects.all()#commonly used to get all the
objects from the model return array of objects
7. return render(request, 'hi.html', {'user':user}) #passing the
objects to the template
8.

2. Handle values in frontend


Basic example
{% load static tailwind_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
{% tailwind_css %}
</head>
<body class="bg-slate-600 text-white">

{% for u in user %}
<div class="user-type">
<img src="{{ u.image.url }}" alt="User Image">
<h3>Name : {{ u.name }}</h3>
<p>Email : {{ u.email }}</p>
</div>
{% endfor %}
</body>
</html>

Onclick data passing coming soon

Relationships in Django
There are three types of relationships are there
i.e,
1)one-to-one
2)one-to-many
3)many-to-many
1) One-to-many
one user profiles can have different reviews
2) #one to Many relationship
3) class ProfileReview(models.Model):
4) RATING_TYPE = [
5) ('1', '1'),
6) ('2', '2'),
7) ('3', '3'),
8) ('4', '4'),
9) ('5', '5'),
10) ]
11) user = models.ForeignKey(User,
on_delete=models.CASCADE)
12) #CASCADE: if user is deleted, all reviews will be
deleted
13) review =
models.CharField(max_length=10,choices=RATING_TYPE)
14) date_added =
models.DateTimeField(default=timezone.now())
15)
16) def __str__(self):
17) return f"User: {self.user}, Review: {self.review}"
18)

2) many-to-many
class UserFollow(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
follower = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='follower')
date_added = models.DateTimeField(default=timezone.now())

def __str__(self):
return f"User: {self.user.name}, Follower:
{self.follower.name}"

Forms in Django

We used forms in Django for linking models and forms and together

Basic form
from django import forms
from .models import Tweet
class TweetForm(forms.ModelForm):
class Meta: # define meta class
model = Tweet
fields = ['tweet', 'photo']#define model fields to be used in
form
Basic imports in views
from django.shortcuts import render
from .models import Tweet
from .forms import TweetForm
from django.shortcuts import get_object_or_404
# Create your views here.
def index(request):
return render(request, 'index.html')

You might also like