Django Introduction
Django is a high-level Python web framework that enables developers to build robust and scalable web applications quickly. It encourages clean and pragmatic design by emphasizing reusable and maintainable code.
Step 1: Installing Django
To start using Django, you need to install it. Use the following command:
pip install django
To confirm that Django has been installed successfully, type:
django-admin --version
Step 2: Creating a Django Project
Once installed, you can create a new Django project using the following command:
django-admin startproject myproject
This will create a directory named myproject with the following structure:
myproject/ manage.py myproject/ __init__.py asgi.py settings.py urls.py wsgi.py
Step 3: Running the Development Server
Navigate to your project folder and run the development server:
cd myproject python manage.py runserver
After running this command, open your browser and go to http://127.0.0.1:8000 to see the default Django welcome page.
Step 4: Creating a Django App
Django organizes code into apps. To create an app, use the following command:
python manage.py startapp myapp
This will create a directory named myapp with the following structure:
myapp/ migrations/ __init__.py admin.py apps.py models.py tests.py views.py
Step 5: Writing a View
In the views.py file of your app, define a simple view function:
from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!")
Step 6: Configuring URLs
Add the new view to your project's URL configuration. Open urls.py in the project folder and update it:
from django.contrib import admin from django.urls import path from myapp.views import home urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), ]
Now, navigate to http://127.0.0.1:8000 in your browser to see "Hello, Django!" displayed on the page.
Step 7: Next Steps
This is just the beginning! With Django, you can:
- Define models for database interaction
- Use Django's powerful admin interface
- Implement templates for dynamic HTML
- Handle forms and user authentication