urls.py
# /music/alubm/add/ url(r'^album/add/$', views.AlbumCreate.as_view(), name="album-add"), # /music/alubm/3/update/ url(r'^album/(?P<pk>\d+)/update/$', views.AlbumUpdate.as_view(), name="album-update"), # /music/alubm/3/delete/ url(r'^album/(?P<pk>\d+)/delete/$', views.AlbumDelete.as_view(), name="album-delete"),
views.py
from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] # default: template_name = <app_name>/<model_name>_form.html 创建、更新、删除的默认模板都是这个,这里为:music/album_form.html class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') #删除成功后,当前页面将不存在了,所以需要重定向一下
models.py
from django.core.urlresolvers import reverse class Album(models.Model): ... def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.pk})
album_form.html ... {% block body %} <div class="container"> <div class="row"> <div class="col-sm-12 sol-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form action="#" method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} {% include 'music/form-template.html' %} </form> </div> </div> </div> </div> </div> {% endblock %
form-template.html 通用模板,可通过include标签引入
{% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="label-control col-sm-2">{{ field.label_tag }}</label> <div class="col-sm-10">{{ field }}</div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-offset-2"> <button type="submit" class="btn btn-success">Submit</button> </div> </div>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django – 模型表单(创建、更新、删除) - Python技术站