rya*_*les 3 django django-models django-views
我正在制作我的第一个 Django 网站,该网站目前为止有一个名为 client 的应用程序,并且我将模板保存在 project_name/clients/templates/clients 中。
就像标题所说,我可以在视图文件中使用 UpdateView 更新模型客户端的实例,并且我认为我可以使用 DeleteView 以相同的方式删除实例,但我收到了前面所述的错误。任何帮助,将不胜感激。我看过其他类似的帖子,但没有任何帮助我解决这个问题
这是我的网址文件:
from django.conf.urls import url
from . import views
app_name = 'clients'
url(r'^$', views.IndexView.as_view(), name='index'),
# /clients/11/... could be any number
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# /clients/viewed/
url(r'^viewed/', views.viewed, name='viewed'),
# /clients/add/
url(r'^add/$', views.ClientCreate.as_view(), name='client-add'),
# /clients/3/update/
url(r'^(?P<pk>[0-9]+)/update$', views.ClientUpdate.as_view(), name='client-update'),
# /clients/8/delete/
url(r'^(?P<pk>[0-9]+)/delete/$', views.ClientDelete.as_view(), name='client-delete'),
]
Run Code Online (Sandbox Code Playgroud)
这是我的views.py中的相关类:
from __future__ import unicode_literals
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render
from .models import Client
class ClientUpdate(UpdateView):
model = Client
fields = ['name', 'age', 'height', 'weight',
'history_of_head_trauma', 'profession', 'is_athlete', 'email']
success_url = reverse_lazy('clients:index')
class ClientDelete(DeleteView):
model = Client
success_url = reverse_lazy('clients:index')
Run Code Online (Sandbox Code Playgroud)
这是我的 index.html 中的 div,其中包含用于更新和删除的按钮:
<div class="panel-footer">
<a type="button" class="btn btn-sm btn-success"><i class="glyphicon glyphicon-envelope"></i></a>
<span class="pull-right">
<a href="{% url 'clients:client-update' pk=client.id %}" type="button" class="btn btn-small btn-info"><i class="glyphicon glyphicon-edit"></i></a>
<a href="{% url 'clients:client-delete' pk=client.id %}" type="button" class="btn btn-small btn-danger"><i class="glyphicon glyphicon-remove"></i></a>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
由于某种原因,当使用 UpdateView 时,html 中的按钮可能只是一个简单的链接,其 href 指向正确的 url,在我的例子中,该链接指向我的视图文件中的 ClientUpdate ...
但对于DeleteView,html 必须位于<form>. 这是我必须更改才能使其工作的唯一代码。我基本上用表格代替了
<a href="{% url 'clients:client-delete' pk=client.id %}"....>
<div class="panel-footer">
<a type="button" class="btn btn-sm btn-success"><i class="glyphicon glyphicon-envelope"></i></a>
<span class="pull-right">
<a href="{% url 'clients:client-update' pk=client.id %}" type="button" class="btn btn-small btn-info"><i class="glyphicon glyphicon-edit"></i></a>
<form action="{% url 'clients:client-delete' pk=client.id %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="client_id" value="{{ client.id }}"/>
<button type="submit" class="btn btn-danger btn-small">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</span>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1792 次 |
| 最近记录: |