【问题标题】:How to update a form and update table cell in Django如何在 Django 中更新表单和更新表格单元格
【发布时间】:2020-01-05 21:19:10
【问题描述】:

我是非常新的 Django 和 python,正在尝试学习和构建一个 webapp。

我想以表格的形式向用户展示一些数据。用户应该能够在表格视图中添加、删除和更新记录。

我能够实现添加、删除部分,但无法更新现有记录。

理想情况下,当单击特定行的“编辑”按钮时,我希望将行数据作为 django 表单填充到模态视图中。但甚至无法从可编辑的表格行中获取基本更新。这是我的示例代码..

我在下面的链接中尝试过,但没有帮助.. 或者可能是我不明白。 Django: updating database row via table cell

models.py


# Create your models here.

class customerDataModel(models.Model):
    customerName = models.CharField(max_length=200)
    custormerLocation = models.CharField(max_length=200)
    custormerAge = models.CharField(max_length=200)
    custormerLanguage = models.CharField(max_length=200)

    def __str__(self):
        return self.customerName

forms.py

from django import forms
from . models import customerDataModel


class addCustomerForm(forms.ModelForm):

    class Meta:
        model = customerDataModel
        fields = ('customerName', 'custormerLocation', 'custormerAge', 'custormerLanguage')

        widgets = {
            'customerName': forms.TextInput(
                attrs={
                    'class': 'form-control'
                    }
                ),
            'custormerLocation': forms.TextInput(
                attrs={
                    'class': 'form-control'
                    }
                ),
            'custormerAge': forms.TextInput(
                attrs={
                    'class': 'form-control'
                    }
                ),

            'custormerLanguage': forms.TextInput(
                attrs={
                    'class': 'form-control'
                    }
                ),


            }

views.py

from django.shortcuts import render
from . forms import addCustomerForm
from . models import customerDataModel
from django.http import HttpResponseRedirect
from django.urls import reverse

# Create your views here.

#from django.http import HttpResponse


def index(request):
    if request.method == 'POST':
        form = addCustomerForm(request.POST)
        if form.is_valid():
            # print("VALID")
            form.save()

    customer_table_data = customerDataModel.objects.all()
    form = addCustomerForm
    return render(request, 'index.html', {'customer_table_data' : customer_table_data ,'form' : form})
    #return HttpResponse("Hello, world. You're at the polls index.")


def delete_customer_row(request, id):
    customerDataModel.objects.filter(id=id).delete()
    return HttpResponseRedirect(reverse('index'))


def edit_customer_row(request, id):

    print('The value in ID is ', id)

    instance = customerDataModel.objects.get(id=id)
    if request.method == "POST":
        form = addCustomerForm(request.POST, instance=instance)
        if form.is_valid():
             print("VALID")
             form.save()
    return HttpResponseRedirect(reverse('index'))

template.html

<!DOCTYPE html>
<html>
<head>
<style>
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {background-color: #f2f2f2;}
</style>
</head>
<body>

<h2>Customer Information</h2>

<form method="POST">

    {% csrf_token %}
     {{ form }}

     <br>
     <button type="submit">Submit</button>
</form>



<div style="overflow-x:auto;">
  <table>
    <tr>
      <th>Customer Name</th>
      <th>Location</th>
      <th>Age</th>
      <th>Laungage</th>
      <th>Action</th>
    </tr>



    {% for rowitem in customer_table_data %}

    <tr>
        <form action="{% url 'edit_customer_row' rowitem.id %}" method="post">
                {% csrf_token %}
        <td>{{rowitem.customerName}}</td>
        <td><div contenteditable>{{rowitem.custormerLocation}}</div></td>
        <td>{{rowitem.custormerAge}}</td>
        <td>{{rowitem.custormerLanguage}}</td>
        <!-- <td><a href="{% url 'edit_customer_row' rowitem.id %}" <button>edit</button></a></td> -->
        <td><input type="submit" value="edit"/></td>
        <td><a href="{% url 'delete_customer_row' rowitem.id %}" <button>delete</button></a></td>
        </form>
    </tr>

    {% endfor %}


  </table>
</div>

</body>
</html>

【问题讨论】:

    标签: html django django-forms


    【解决方案1】:

    这种方法的问题是,当用户输入的数据在服务器上验证失败时,你会怎么做?如果您重定向回表格视图,它如何告诉用户它为什么忽略他的要求?

    在某种类似的情况下,我的方法是最初隐藏在表格底部(或顶部,如果您愿意)的 Django 表单。使用一些 Javascript 从模式弹出窗口中填充表单的字段,并发布它。在服务器端,一切都以通常的方式进行。如果验证失败,表格视图会在表单中返回错误,并且 Javascript(在 Jquery onReady 上下文中)可以立即取消隐藏表单并确保错误消息显示附加到先前输入的数据。用户可以在表单中编辑他的响应,或者可以再次单击表格行从头开始(模式将覆盖表单中显示的旧数据)。

    所涉及的工作是在客户端 JQuery 端。我不认为 Django 端有什么不寻常的地方。

    更简单的方法是第二次往返服务器。在表格中,每一行都有一个可点击的“更新”图标,这是一个指向常规 FormView 的链接,例如“/foo/44/update”({{url "foo:foo_update" pk=object.pk}} 或模板中的类似内容),44 是object.pk在该行中表示的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多