Django Imp
Django Imp
Project creation:
First install the uv package as everything should be in a virtual environment.
Command :
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.
Steps:
But before rendering any thing in Django using templates first of all main
project should know where templates exists
If your template exists in any other folder inside templates then don’t
forget to specify folder name of that template where it resides
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 :
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 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
Note:
For handling images one short setting is needed in settings.py
i.e,
After you can see all the fields that are important at start
{% 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>
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')