Model Form Example - Django Typing CST Test
Loading…
Model Form Example — Django Code
Use Django ModelForm to create a new model instance.
# models.py
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=50)
# forms.py
from django.forms import ModelForm
from .models import Item
class ItemForm(ModelForm):
class Meta:
model = Item
fields = ['name']
# views.py
from django.shortcuts import render, redirect
from .forms import ItemForm
def add_item(request):
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = ItemForm()
return render(request, 'add_item.html', {'form': form})
# add_item.html
"""
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<button type='submit'>Add</button>
</form>
"""Django Language Guide
Django is a high-level Python web framework that encourages rapid development, clean design, and pragmatic code. It includes built-in tools for ORM, authentication, routing, and templating.
Primary Use Cases
- ▸Building dynamic web applications and websites
- ▸Developing RESTful APIs with Django REST Framework
- ▸Rapid prototyping of web projects
- ▸CMS and admin dashboard applications
- ▸E-commerce and SaaS applications
Notable Features
- ▸Object-relational mapping (ORM) for database operations
- ▸Built-in authentication and user management
- ▸Automatic admin interface
- ▸Template system for HTML generation
- ▸URL routing and middleware support
Origin & Creator
Django was created by Adrian Holovaty and Simon Willison in 2005 at the Lawrence Journal-World newspaper.
Industrial Note
Django is used heavily in industries requiring rapid prototyping, content management systems, and scalable web applications, e.g., news, e-commerce, and SaaS.