【问题标题】:Update table values based on which button clicked根据单击的按钮更新表值
【发布时间】:2022-01-18 09:16:24
【问题描述】:

我有一个DetailView,它显示了来自交易 ID、名称、created_date、.... 和状态的所有交易信息。在此页面中,我有 3 个按钮,它们是取消、批准和拒绝。

我想要做的是当我点击按钮取消状态更改为“已取消”时,有些人会拒绝并批准将状态更改为“拒绝”和“成功”。

我该怎么做?

我尝试在模板中添加带有隐藏输入和方法帖子的表单,但提交后显示 405 错误页面。

html

{% if transaction.status == "Approval" or transaction.status == "Rejected" or transaction.status == "Failed"  %}
<form method="post">
    {% csrf_token %}
    <input type="hidden" name="status" value="Cancelled">
    <button type="submit" class="btn btn--danger">
        <i class="btn__icon">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                stroke-linecap="round" stroke-linejoin="round"
                class="feather feather-x">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
        </i>
        <span>Cancel</span>
    </button>
</form>
{%endif%}

查看

class DetailTransaction(LoginRequiredMixin, SuccessMessageMixin, DetailView):
    model = Transaction
    field = ['status']
    template_name = 'transaction/transaction-detail.html'
    form_class = TransactionCreateForm
    success_url = reverse_lazy("transaction-view")
    success_message = "Transaction updated successfully."

    def get_queryset(self):
        queryset = Transaction.objects.all()
        return queryset

    def form_valid(self, form):

    status = form.cleaned_data["status"]
    transaction = Transaction(
    status = status
    )
    transaction.save()

    return super(DetailTransaction, self).form_valid(form)

型号

class Transaction(models.Model):
        Status = (
        ('Approval', 'Approval'),
        ('Rejected', 'Rejected'),
        ('Success', 'Success'),
        ('Failed', 'Failed'),
        ('Cancelled', 'Cancelled'),
    )
    status = models.CharField(max_length=10, choices=Status, default='Approval')

【问题讨论】:

  • 请添加您的代码(视图、模板和模型中的相关代码)。否则很难知道到底出了什么问题。一般来说,您的解决方案听起来是对的。
  • @Risadinha,我已经添加了我的代码,几天前我尝试了这个解决方案,我尝试重新创建它以将其发布在这里。

标签: python django django-models django-views django-templates


【解决方案1】:

只是猜测,因为您没有发布任何代码。

405 表示你的视图不接受 POST 请求。

在 Django 中有不同的方法来解决这个问题。

装饰器

使用require_http_methods 装饰器,如https://docs.djangoproject.com/en/4.0/topics/http/decorators/#allowed-http-methods 中所述。

更新视图

如果您喜欢基于类的通用视图,请使用https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-editing/#django.views.generic.edit.UpdateView

即使您只想更改模型的单个字段,也可以使用 UpdateViews。

【讨论】:

  • 我尝试使用 UpdateView 它给了我这个错误 __init__() got an unexpected keyword argument 'instance'
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2019-09-23
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 2014-01-17
相关资源
最近更新 更多