Django Tutorial: Quickly Build Your First Web Application
Django Tutorial: Quickly Build Your First Web Application
Django is a high-level Python Web framework that aims for rapid development and clean design. It follows the Model-Template-View (MTV) architecture, encouraging code reuse and componentization. This guide will walk you step-by-step through creating a simple Django application to get you started quickly.
1. Environment Setup
First, you need to make sure you have Python installed on your system. Django recommends using Python 3.6 or higher.
1.1 Install Python
If you don't have Python installed on your system, you can download and install it from the Python official website.
1.2 Create a Virtual Environment
To isolate dependencies between different projects, it is strongly recommended to use a virtual environment.
-
Open a terminal or command prompt.
-
Create a project directory, for example
myproject:mkdir myproject cd myproject -
Create and activate the virtual environment:
python3 -m venv venv # or python -m venv venv source venv/bin/activate # Linux/macOS venv\Scripts\activate # WindowsAfter activating the virtual environment, your terminal prompt will display
(venv), indicating that you are using the virtual environment.
1.3 Install Django
In the activated virtual environment, use pip to install Django:
pip install Django
Verify that the installation was successful:
python -m django --version
You should be able to see the Django version number.
2. Create a Django Project
After installing Django, you can create a new Django project.
-
Still in your project directory (
myproject), run the following command:django-admin startproject mysiteThis will create a directory named
mysitein themyprojectdirectory, containing the skeleton files of the Django project. -
Enter the
mysitedirectory:cd mysite -
The Django project directory structure is as follows:
mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.pymanage.py: A command-line tool for managing Django projects.mysite/: A Python package containing project configurations.__init__.py: An empty file that tells Python that the directory should be treated as a Python package.settings.py: Project configuration file, such as database settings, debug mode, etc.urls.py: URL routing configuration, mapping URLs to view functions.asgi.py: ASGI (Asynchronous Server Gateway Interface) configuration file for deploying asynchronous applications.wsgi.py: WSGI (Web Server Gateway Interface) configuration file for deploying traditional synchronous applications.
3. Starting the Development Server\n\nDjango comes with a lightweight development server to facilitate local development and testing.\n\n1. In the mysite directory, run the following command:\n\n bash\n python manage.py runserver\n \n\n2. Open your browser and visit http://127.0.0.1:8000/. You should see the page ```python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
```
3. Include myapp/urls.py into mysite/urls.py:
```python
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')), # Add the URL configuration for myapp
]
```
4. Visit http://127.0.0.1:8000/myapp/. You should see the "Hello, Django!" page.
6. Create a Model
Let's create a simple model to store some data.
-
Edit the
myapp/models.pyfile and add the following code:from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_textThis defines a model named
Questionwith two fields:question_text(CharField) andpub_date(DateTimeField). -
Create and apply database migrations:
python manage.py makemigrations myapp python manage.py migrateThe
makemigrationscommand creates migration files based on your model, and themigratecommand applies the migrations to the database.
7. Use the Django Admin Interface
Django provides a powerful admin interface for easily managing your data.
-
Create a superuser:
python manage.py createsuperuserFollow the prompts to enter a username, email, and password.
-
Edit the
myapp/admin.pyfile and register theQuestionmodel:from django.contrib import admin from .models import Question admin.site.register(Question) -
Visit
http://127.0.0.1:8000/admin/and log in with the superuser you created. You should see the "Questions" module, where you can add, edit, and delete questions.
8. Use Templates
Using templates allows you to generate HTML pages more flexibly.1. Create a directory named templates under the myapp directory, and create a directory named myapp under the templates directory (myapp/templates/myapp).
-
Create a file named
index.htmlin themyapp/templates/myappdirectory and add the following code:
Hello, Django!
The current time is: {{ current_time }}
```
3. Edit the myapp/views.py file to use the template:
```python
from django.shortcuts import render
import datetime
def index(request):
now = datetime.datetime.now()
return render(request, 'myapp/index.html', {'current_time': now})
```
The `render` function loads the template and passes the data to the template for rendering.
4. Revisit http://127.0.0.1:8000/myapp/. You should see a page containing the current time.
9. Conclusion
Through this guide, you have learned the basic concepts and usage of Django, including setting up the environment, creating projects and applications, defining models, creating views, and using templates. This is just the beginning. Django provides rich features, and you can continue to learn and explore to build more complex Web applications.





