Django Basics and App Structure Guide
Django Basics and App Structure Guide
Install:
Create project:
Run server:
Create app:
Structure:
- [Link]
- [Link]
- [Link]
- templates/
Page 3: Django Models
class Person([Link]):
name = [Link](max_length=100)
age = [Link]()
Migrate:
[Link]:
def index(request):
[Link]:
Use render():
{{ variable }}
{{ item }}
{% endfor %}
In Django, use the 'render()' function within a view to generate an HTML template response. For example, 'return render(request, 'index.html', {'name': 'Alice'})' loads the 'index.html' template from the 'templates/' directory and passes a context dictionary containing variables like 'name' .
A typical Django app includes several critical modules, such as 'models.py' for defining data models, 'views.py' for handling request/response logic, 'urls.py' for routing, and a 'templates/' directory for HTML templates .
The 'urls.py' file in a Django app defines the URL patterns for routing requests to the appropriate view functions. It imports views and associates them with URL paths using the 'path()' function, enabling the application to respond correctly to various requests .
In Django templates, variables are dynamically inserted using the double curly braces syntax '{{ variable }}'. These variables are passed from views through context dictionaries and are replaced with their values during template rendering .
The 'makemigrations' command in Django generates new migration files based on changes made to models in 'models.py'. The 'migrate' command applies these changes to the database, ensuring that the schema aligns with the current model definitions .
To iterate over a list in a Django template, use the template syntax: '{% for item in list %} {{ item }} {% endfor %}'. This allows the template to loop through 'list' and render each 'item' within the specified loop block .
To create a new Django project, use the command 'django-admin startproject mysite'. After creating the project, navigate into the project directory and run the server with 'python manage.py runserver' .
Define a simple view in 'views.py' like 'def index(request): return HttpResponse("Hello Django")'. Then map it to a URL path in 'urls.py' by importing the view and using 'urlpatterns = [ path('', views.index) ]' .
The command 'python manage.py startapp myapp' is used to create a new Django app. It generates essential components like 'models.py', 'views.py', 'urls.py', and a 'templates/' directory .
Define a Django model by creating a class in 'models.py', for example, 'class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField()'. After defining the model, run 'python manage.py makemigrations' to create migration scripts and 'python manage.py migrate' to apply these migrations to the database .