Py学习  »  Django

如何在django中更新表单和表单元格

Kevin • 4 年前 • 1122 次点击  

我是非常新的django和python,试图学习和构建一个webapp。

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

我可以实现添加,删除部分,但是,不能让我的头周围更新现有的记录。

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

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

模特儿


# 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

表单

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'
                    }
                ),


            }

VIEW

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'))

模板.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>

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/45450
 
1122 次点击  
文章 [ 1 ]  |  最新文章 4 年前
nigel222
Reply   •   1 楼
nigel222    4 年前

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

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

所涉及的工作在客户端jquery端。我不认为在Django那边有什么不寻常的事情。

更简单的方法是第二次往返服务器。在表中,每行有一个可点击的“update”图标,它是一个到传统表单视图的链接,比如“/foo/44/update”( {{url "foo:foo_update" pk=object.pk}} 或模板中的类似内容),44表示 object.pk 表示在该行中的对象的。