从模板传递对象以使用Django进行查看 [英] Passing objects from template to view using Django

查看:554
本文介绍了从模板传递对象以使用Django进行查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出以下应用程序的架构:

I am trying to figure out the architecture for the following app:


  1. 给用户一张桌子。

  2. 每个表单元格都有几个用户填写的字段。

  3. 有一个常规提交按钮:点击所有输入数据(连同一些计算

以下是以下问题:


  1. 我可以将数据结构组织为一组对象,方法是每个对象都对应一个表单元格,而主对象将最终传递给Django视图,将会是一组这些对象?

  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?

If so, how to pass the Master object from a template to view using Django?

谢谢。

推荐答案

<强> 1。可以在HTML / JS中创建一个对象,其成员将包含字段中的数据?

您不能在html / JS中创建对象,但是您可以构建代码以在Django中显示或请求数据。

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.

举个例子,你有一个模型Foo

Say for example, you have a model Foo

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

您的模板看起来像这样

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

如果您填写字段并单击提交,那么您可以处理视图中的数据。 / p>

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

最后一点也回答了问题2,我想。希望这有帮助。

That last bit also answered question 2, i think. Hope this helps.

这篇关于从模板传递对象以使用Django进行查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆