简体   繁体   English

使用Django将对象从模板传递到视图

[英]Passing objects from template to view using Django

I am trying to figure out the architecture for the following app: 我试图找出以下应用程序的体系结构:

  1. The user is presented with a table. 向用户显示一个表格。
  2. Each table cell has several fields the user will be filling in. 每个表格单元都有用户要填写的几个字段。
  3. There is a general submit button: when clicked on all the input data (along with some calculated data per cell based on the input values) should pass to a Django view. 有一个常规的提交按钮:单击所有输入数据(以及基于输入值的每个单元格的一些计算数据)时,应传递到Django视图。

Here are the following questions: 以下是以下问题:

  1. Can I organize the data structure as a set of objects in a way that each object will correspond to a table cell, whereas the Master object, that will eventually be passed to the Django view, will be a set of those objects? 我是否可以将数据结构组织为一组对象,以使每个对象都对应于一个表格单元,而最终将传递给Django视图的Master对象将是这些对象的集合?

  2. If so, how to pass the Master object from a template to view using Django? 如果是这样,如何使用Django将Master对象从模板传递到视图?

Thanks. 谢谢。

1. Is it possible to create an object in HTML/JS whose members will contain data from the fields? 1.是否可以在HTML / JS中创建一个对象,该对象的成员将包含来自字段的数据?

You can't create an object in html/JS, but you can build your code up to display or request data from an object in Django. 您无法在html / JS中创建对象,但可以构建代码以显示或从Django中的对象请求数据。

Say for example, you have a model Foo 假设您有一个Foo模型

class Foo(models.Model):
    GENDER = (
      ('F', 'Female'),
      ('M', 'Male'),
    )
    name = models.CharField(max_length=150)
    gender = models.CharField(max_length=1, choices=GENDER)

And your template looks like this 您的模板如下所示

<body>
<form action="?" method="post">
<table>
    <tr>
        <td>Name</td>
        <td><input type="text" name="name" maxlength="150" /></td>
    </tr>
    <tr>
        <td>Gender</td>
        <td>
            <select name="gender">
                <option value="F">Female</option>
                <option value="M">Male</option>
            </select>
        </td>
    </tr>
</table>
<input type="submit">
</form>
</body>

If you fill in the fields and click submit, then you can handle the data in your view. 如果填写字段并单击提交,则可以在视图中处理数据。

def add_foo(request):
    if request.method == "POST": # Check if the form is submitted
        foo = Foo() # instantiate a new object Foo, don't forget you need to import it first
        foo.name = request.POST['name']
        foo.gender = request.POST['gender']
        foo.save() # You need to save the object, for it to be stored in the database
        #Now you can redirect to another page
        return HttpResponseRedirect('/success/')
    else: #The form wasn't submitted, show the template above
        return render(request, 'path/to/template.html')

That last bit also answered question 2, i think. 我认为,最后一点也回答了问题2。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM