django Class-based views 实现表的增删改查(Create, Update, Delete)

刚开始学习django,本系列文章记录学习历程

1、创建django工程,创建名为crud的app,此处略过

2、 修改models.py

 
  
class employee(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=60)
    city = models.CharField(max_length=60)
    email = models.EmailField(max_length=30)
    phone = models.CharField()
    wechat = models.CharField(max_length=30)
    QQ = models.CharField()
    def __unicode__(self):
        return self.name
    class Meta:
        ordering = ["-id"]

3、配置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crud',
]

4、数据迁移

python manage.py makemigrations crud
python manage.py migrate crud

5、修改urls,views

crud中的urls

 
  
from django.conf.urls import url
from crud import views

urlpatterns = [
    url(r'^$', views.EmployeeList.as_view(), name='employee_list'),
    url(r'^add', views.EmployeeCreate.as_view(), name='employee_add'),
    url(r'^update/(?P\d+)$', views.EmployeeUpdate.as_view(), name='employee_update'),
    url(r'^delete/(?P\d+)$', views.EmployeeDelete.as_view(), name='employee_delete'),
    url(r'employee_detail/(?P\d+)/$', views.EmployeeDetail.as_view(), name='employee_detail'),
]

工程中urls

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^crud/', include('crud.urls')),
]

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, redirect

# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import TemplateView,ListView
from django.utils import timezone
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from crud.models import employee

class EmployeeList(ListView):
    model = employee

class EmployeeCreate(CreateView):
    model = employee
    success_url = reverse_lazy('employee_list')
    fields = ['id', 'name', 'address', 'city', 'email', 'phone', 'wechat', 'QQ']
    def add(request):
        form = employee(request.POST or None)
        if form.is_valid():
            instance.save()
        context = {
            'form': form,
        }
        #如果没有有效提交,则仍留在原来页面
        return render(request, 'employee_list.html',  context)

class EmployeeUpdate(UpdateView):
    model = employee
    success_url = reverse_lazy('employee_list')
    fields = ['id', 'name', 'address','city', 'email', 'phone','wechat','QQ']

class EmployeeDelete(DeleteView):
    model = employee
    success_url = reverse_lazy('employee_list')

class EmployeeDetail(DetailView):
    model = employee   #将 model 指定为Publisher,告诉 Django 我要获取的模型是 Publisher。
    context_object_name = 'employee_detail'   #指定获取的模型列表数据保存的变量名。这个变量会被传递给模板。
    def get_context_data(self, **kwargs):
        context = super(EmployeeDetail, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

6、新建模板

employee_list.html


<ul>
    {% for emp in object_list %}
    <li>{{ emp.id }}     {{ emp.name }}    {{ emp.address }}   {{ emp.city }}    
        {{ emp.email }}    {{ emp.phone }}   {{ emp.wechat }}    {{ emp.QQ }}:
    <a href="{% url "employee_update" emp.id %}">修改a>
    <a href="{% url "employee_delete" emp.id %}">删除a>
    li> 
    {% endfor %}
ul>

<a href="{% url "employee_add" %}">新增a>


employee_form.html

    <title>Titletitle>
    <form method="post">
        <table>
            {% csrf_token %}
            {{ form }}
        table>
    <input type="submit" value="Submit" />
form>

employee_confirm_delete.html

<form method="post">{% csrf_token %}
确实要删除 "{{ object }}" ?
<input type="submit" value="Submit" />
form>

employee_detail.html

<h1>你好,{{ object.name }}h1>
<h2>工号:{{ object.id }}h2>
<p>姓名:{{ object.name }}p>
<p>邮箱地址:{{ object.email }}p>
<p>所在城市: {{ object.city }}p>
<p>电话号码: {{ object.phone }}p>
<p>详细地址: {{ object.address }}p>
<p>微信: {{ object.wechat }}p>
<p>QQ: {{ object.QQ }}p>

7、启动服务python manage.py runserver 

浏览器中输入 http://127.0.0.1:8000/crud/ 即可对员工进行增加、删除、修改

tips:

1、注意模板位置

2、urls中引入相应的模块







你可能感兴趣的:(django)