How to build a simple system using Django?
The steps for building a simple system using Django are as follows:
- To install Django, ensure Python and pip are already installed, then use the command line to run pip install Django.
- To create a Django project, navigate to the desired directory in the command line and then run “django-admin startproject projectname” to create a new Django project.
- To create an application, navigate to the project directory and run “python manage.py startapp appname”.
- Define a model: Define a data model in the models.py file of the application directory, such as creating a user model.
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
password = models.CharField(max_length=100)
- Migrate database: Run ‘python manage.py makemigrations’ to generate migration files, then run ‘python manage.py migrate’ to apply database migration.
- Create a view: Define a view function in the views.py file of the application directory, for example, create a user list view.
from django.shortcuts import render
from .models import User
def user_list(request):
users = User.objects.all()
return render(request, 'user_list.html', {'users': users})
- Create a template: Create a folder named “templates” in the application directory, and inside it, create a template file named “user_list.html” to display the list of users.
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
- Set up URL routing: In the urls.py file in the project directory, configure the URL routing to associate the user list view with a URL path.
from django.urls import path
from appname.views import user_list
urlpatterns = [
path('users/', user_list, name='user_list'),
]
- Run server: Start the Django development server by running “python manage.py runserver” in the command line.
- Access the system: Enter http://localhost:8000/users/ in the browser to access the user list page.
Here are the basic steps to set up a simple system using Django. You can continue to add models, views, and templates according to your needs in order to build a more complex system.