Creating a basic web application using Django is a fundamental skill for computer science students. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This study note will guide you through the process of creating a basic web application using Django, breaking down complex ideas into easily digestible sections.
Before starting, ensure you have the following:
pip install django
)A virtual environment helps manage dependencies for different projects separately.
python -m venv myenv
myenv\Scripts\activate
source myenv/bin/activate
Tip
Always use a virtual environment to avoid dependency conflicts between projects.
With the virtual environment activated, install Django:
pip install django
django-admin startproject myproject
cd myproject
python manage.py runserver
http://127.0.0.1:8000/
. You should see the Django welcome page.Note
If you see the Django welcome page, your setup is correct.
python manage.py startapp myapp
myproject/settings.py
.'myapp'
to the INSTALLED_APPS
list:INSTALLED_APPS = [
...
'myapp',
]
myapp/views.py
.from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, World!")
myapp/urls.py
(create this file if it doesn't exist).from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
myproject/urls.py
and modify it:from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
python manage.py runserver
http://127.0.0.1:8000/
. You should see "Hello, World!".Example
In this example, we've created a basic Django web application that displays "Hello, World!" at the root URL.
myapp/models.py
.from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
myapp/admin.py
:from django.contrib import admin
from .models import Post
admin.site.register(Post)
http://127.0.0.1:8000/admin/
.Common Mistake
Forgetting to register models in the admin interface is a common mistake that prevents them from being managed through the admin site.
In this study note, we've covered the basics of creating a Django-based web application. We started by setting up a virtual environment, installing Django, and creating a project. We then created an app, defined a view, mapped URLs, and set up a model with database migrations. Finally, we registered the model in the admin interface.
By following these steps, you can create a basic Django web application and expand upon it with more complex functionalities as you gain more experience.
Tip
Practice regularly and refer to the official Django documentation for more advanced topics and best practices.