作业

5月27号

## index.html(部分)
<table class="table table-bordered table-hover table-striped">
    <thead>
        <th>ID</th>
        <th>书名</th>
        <th>作者</th>
        <th>价格</th>
        <th class="text-center">操作</th>
    </thead>
    <tbody>
        {% for book in booklist %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }}</td>
                <td>{{ book.price }}</td>
                <td class="text-center">
                    <a href="{% url 'edit' book.id %}" class="btn btn-success btn-sm">编辑</a>
                    <a href="{% url 'delete' book.id %}" class="btn btn-danger btn-sm">删除</a>
                </td>
            </tr>
        {% endfor%}
    </tbody>
</table>


## edit.html
<body>
<h1 class="text-center">编辑</h1>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <form action="" method="post">
                <p>bookname:<input type="text" name="bookname" class="form-control" value="{{ obj.name }}"></p>
                <p>author:<input type="text" name="author" class="form-control" value="{{ obj.author }}"></p>
                <p>price:<input type="text" name="price" class="form-control" value="{{ obj.price }}"></p>
                <input type="submit" class="btn btn-info btn-block" value="编辑">
            </form>
        </div>
    </div>
</div>
</body>


## views.py
from django.shortcuts import HttpResponse, render, redirect, reverse
from app01 import models

# Create your views here.
def index(request):
    booklist = models.Book.objects.all().values("id", "name", "author", "price")
    return render(request, 'index.html', locals())

def delete(request, bookid):
    models.Book.objects.filter(id=bookid).delete()
    return redirect('/index/')

def edit(request, bookid):
    obj = models.Book.objects.filter(id=bookid).first()
    if request.method == 'POST':
        bookname = request.POST.get('bookname')
        author = request.POST.get('author')
        price = request.POST.get('price')
        models.Book.objects.filter(id=bookid).update(name=bookname, author=author, price=price)
        return redirect('/index/')
    return render(request, 'edit.html', locals())


## urls.py
from django.conf.urls import url
from django.contrib import admin
from app01.views import *

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', index),
    url(r'^index/', index),
    url(r'^delete/(?P<bookid>d+)/', delete, name='delete'),
    url(r'^edit/(?P<bookid>d+)/', edit, name='edit'),
]
原文地址:https://www.cnblogs.com/chenwenyin/p/12967063.html