1 models.py
from django.contrib.gis.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
address = models.CharField(max_length=100)
phone = models.CharField(max_length=50)
2 admin.py
from django.contrib import admin
from .models import Contact
admin.site.register(Contact)
3 views.py
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Contact
class ContactList(ListView):
model = Contact
class ContactDetail(DetailView):
model = Contact
class ContactCreate(CreateView):
model = Contact
success_url = reverse_lazy('contact_list')
success_message = "contact successfully created!"
class ContactUpdate(UpdateView):
model = Contact
success_url = reverse_lazy('contact_list')
success_message = "contact successfully created!"
class ContactDelete(DeleteView):
model = Contact
success_url = reverse_lazy('contact_list')
success_message = "contact successfully created!"
4 Templates
contact_list.html
Contacts
Name | Address | Phone | Actions | |
---|---|---|---|---|
{{ contact.name }} | {{ contact.email }} | {{ contact.address }} |
details edit delete |
contact_details.html
Contact Details
Name: {{object.name}}
Email: {{object.email}}
Address: {{object.address}}
Phone: {{object.phone}}
contact_form.html
Contact Update
contact_confirm_delete.html
Contact Delete?
5 urls.py
from django.urls import path
from . import views
urlpatterns = [
# [...]
path('contacts', views.ContactList.as_view(), name='contact_list'),
path('contact/', views.ContactDetail.as_view(), name='contact_detail'),
path('create', views.ContactCreate.as_view(), name='contact_create'),
path('update/', views.ContactUpdate.as_view(), name='contact_update'),
path('delete/', views.ContactDelete.as_view(), name='contact_delete'),
]
Passing extra context in views
def get_context_data(self, *args, **kwargs):
context = super(CBV_NAME, self).get_context_data(*args, **kwargs)
new_context_entry = "here it goes"
context["new_context_entry"] = new_context_entry
return context
# or
self.extra_context["another_one"] = "here goes more"