Django
Django
Here are some of the key features that make Django a powerful choice
for web development:
To get started with Django, you need to have Python installed on your
system. Here are the basic steps to set up a Django project:
sh
pip install django
sh
sh
Virtual Environment
Step-by-Step Guide
sh
python --version
If you don't have Python installed, you can download it from the
official Python website.
sh
pip install virtualenv
sh
virtualenv myenv
Replace myenv with the name you want for your virtual
environment.
myenv\Scripts\activate
source myenv/bin/activate
Before you begin, ensure you have Python and virtualenv installed. Set
up a virtual environment to manage your project dependencies and keep
your project isolated.
sh
django-admin startproject projectname
sh
python manage.py startapp appname
5.Defining Models
Define your database models in the models.py file of your app. Models
represent the structure of your data and allow Django to generate SQL
queries automatically.
Once your models are defined, create and apply migrations to update
your database schema:
sh
python manage.py makemigrations
python manage.py migrate
7. Creating Views
Define your views in the views.py file of your app. Views handle user
requests and return responses, such as rendering templates or returning
JSON data.
8. Mapping URLs
Create URL patterns in the urls.py file of your app to map views to
specific URLs. Include your app’s URL patterns in the project’s main
urls.py file.
9. Creating Templates
Add static files (e.g., CSS, JavaScript, images) to your project in a static
directory. Configure static file handling in your settings.py file.
Write tests for your app in the tests.py file. Use Django’s testing
framework to ensure your code works as expected:
This directory is the container for your entire Django project. It holds the
settings, URL configurations, and other project-level components.
myapp/:
o __init__.py: Makes this directory a Python package.
o admin.py: Used for registering your models with the Django
admin interface. This makes your models manageable
through the admin panel.
o apps.py: Contains configuration for your app.
o migrations/: This directory stores migration files. These files
are how Django tracks and applies changes to your
database schema (when you modify your models).
__init__.py: Empty, makes the migrations directory a
package.
o models.py: Defines the data models for your app. These
models represent the structure of the data you'll be storing in
your database.
o tests.py: Used for writing unit tests for your app.
o views.py: Contains the view functions (or classes) that
handle incoming web requests and return responses (usually
HTML, JSON, etc.). This is where the logic of your app
resides.
o urls.py (Optional, but Highly Recommended): You can
create a urls.py file inside your app to define URL patterns
specific to that app. This is good practice for organizing your
URLs. If you don't have this file, you'll define all your URL
patterns in the project-level urls.py.
Example Workflow:
Example:Hello world
Step 1: Set Up Your Environment
python --version
virtualenv myenv
o On Windows:
myenv\Scripts\activate
o On macOS/Linux:
source myenv/bin/activate
sh
pip install django
sh
django-admin startproject myproject1
cd myproject
sh
python manage.py startapp myapp
python
# myproject/settings.py
INSTALLED_APPS = [
...
'myapp',]
1. myapp/views.py:
def home(request):
return HttpResponse("hello world")
2. myapp/urls.py:
urlpatterns = [
path(' ', views.home, name='home'),
]
3. myproject/urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
class Student(models.Model):
name = models.CharField(max_length=200)
age = models.IntegerField()
email = models.EmailField(blank=True,
null=True)
grade = models.CharField(max_length=50,
blank=True, null=True)
def __str__(self):
return self.name
# myapp/admin.py
admin.site.register(Student)
# myapp/views.py
def student_list(request):
students = Student.objects.all()
return render(request,
'myapp/student_list.html', {'students':
students})
def student_create(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('student_list')
else:
form = StudentForm()
return render(request, 'student_form.html',
{'form': form})
# myapp/forms.py
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
# myapp/urls.py
urlpatterns = [
path('', views.student_list,
name='student_list'),
path('create/', views.student_create,
name='student_create')
]
# myproject/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
path('', include('myapp.urls')), # Add this
line to handle the root URL
]
# myapp/templates/myapp/student_list.html
<h1>Student List</h1>
<a href="{% url 'student_create' %}">Create
Student</a>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.email }}</td>
<td>{{ student.grade }}</td>
</tr>
{% endfor %}
</tbody>
</table>
python –m venv dj
dj\Scripts\activate
Bash
Bash
Bash