Passing objects from template to view using Django

核能气质少年 提交于 2019-12-10 11:45:13

问题


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.

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?

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

Thanks.


回答1:


1. Is it possible to create an object in HTML/JS whose members will contain data from the fields?

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.

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)

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. Hope this helps.



来源:https://stackoverflow.com/questions/16067603/passing-objects-from-template-to-view-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!