在Django中使用更新和删除按钮创建表单

时间:2018-10-30 19:26:14

标签: javascript html css django forms

当前表单会适当更新,但是“删除”按钮执行的操作与“更新”按钮相同。

我希望使用删除按钮从数据库中删除选定的值。我尝试过为按钮分配值,以及将按钮替换为'a'标签。

这是员工更新页面:

<h5>Edit Work Record</h5>
    <div class="divider"></div>
    <div class="divider"></div>
    <form method="post" action="{% url 'employd:workrecordupdate' view.object.pk %}">
        <div class="row">
            {% csrf_token %}
            {{ form | materializecss:'s6' }}
            <div class="col s6 left-align">
                <button type="submit" class="waves-effect waves-yellow green lighten-2 btn-small">
                    <i class="material-icons left">save</i>update
                </button>
            </div>
            <div class="col s6 right-align">
                    <!-- <a class="waves-effect waves-darken btn-small red" href="delete">delete</a> -->
                <button type="submit" value="delete" class="waves-effect waves-darken btn-small red">
                    <i class="material-icons left">delete</i>delete
                </button>
            </div>
        </div>
    </form>

这对应于我的urls.py中的以下链接:

# ex: /employd/wr/12 -- Update a WorkRecord
path('wr/<int:pk>/', views.WorkRecordUpdateView.as_view(),
     name='workrecordupdate'),
# ex: /employd/wr/create -- Create a new WorkRecord
path('wr/create', views.WorkRecordCreate.as_view(), name='workrecordcreate'),
# ex: /employd/wr/delete -- Delete an existing WorkRecord
path('wr/<int:pk>/delete', views.WorkRecordDelete.as_view(),
     name='workrecorddelete'),

这些直接指向以下视图:

class WorkRecordUpdateView(SuccessMessageMixin, generic.UpdateView):
""" Display WorkRecord update form, for use inside a modal """
model = WorkRecord
fields = '__all__'
template_name_suffix = '_update'
success_message = "Update successful."

def get_success_url(self):
    return self.request.META.get('HTTP_REFERER')

class WorkRecordDelete(SuccessMessageMixin, generic.DeleteView):
""" Deletes a WorkRecord, with confirmation """
model = WorkRecord
template_name = '_delete_confirm.html'

def get_success_message(self, cleaned_data):
    return "Work Record \"%s\" was successfully deleted." % self.object

def get_success_url(self):
    return self.request.META.get('HTTP_REFERER')

1 个答案:

答案 0 :(得分:0)

您的按钮在form标记内,因此它被解释为表单的一部分。将删除按钮放在表单外部,然后将其包装在带有url模式的标签中,以用作删除视图。