Masonite 熟悉步骤小记录 (七、更新和删除文章)
控制器中添加方法
masapp/app/http/controllers/PostController.py
:
def update(self, view: View, request: Request):
post = Post.find(request.param('id'))
return view.render('update', {'post': post})
def store(self, request: Request):
post = Post.find(request.param('id'))
post.title = request.input('title')
post.body = request.input('body')
post.save()
return 'post updated'
新建视图模版
(env) $ craft view update
masapp/resources/templates/update.html
:
<form action="/post/{{ post.id }}/update" method="POST">
{{ csrf_field }}
<label for="">Title</label>
<input type="text" name="title" value="{{ post.title }}"><br>
<label>Body</label>
<textarea name="body">{{ post.body }}</textarea><br>
<input type="submit" value="Update">
</form>
添加路由
masapp/routes/web.py
Get('/post/@id/update', 'PostController@update'),
Post('/post/@id/update', 'PostController@store'),
完成了「控制器方法、视图、路由」这三样的编写之后,可以进入 localhost:8000/post/1/update 里面重新输入一些文本进去,再在数据库中的 posts 数据表中刷新查看,可以看到之前的文章存储内容被改变了。
删除方法
masapp/app/http/controllers/PostController.py
:
from masonite.request import Request
...
def delete(self, request: Request):
post = Post.find(request.param('id'))
post.delete()
return 'post deleted'
masapp/routes/web.py
:
Get('/post/@id/delete', 'PostController@delete'),
在这里使用了 GET 路由,使用 POST 方法会更好,但是为简单起见,先用 GET 吧。
masapp/resources/templates/update.html
模版中增加一个删除链接 <a href="/post/{{ post.id }}/delete"> Delete </a>
:
<form action="/post/{{ post.id }}/update" method="POST">
{{ csrf_field }}
<label for="">Title</label>
<input type="text" name="title" value="{{ post.title }}"><br>
<label>Body</label>
<textarea name="body">{{ post.body }}</textarea><br>
<input type="submit" value="Update">
<a href="/post/{{ post.id }}/delete"> Delete </a>
</form>
现在可以去 localhost:8000/post/1/update 删除文章了,找到刚才添加的链接并点击,这相当于访问了删除文章的页面:localhost:8000/post/1/delete 可以在数据库中刷新 posts 数据表,会发现 id=1 的文章消失了。
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由 Galois
于 4年前 加精