Passing objects from template to view using Django

守給你的承諾、 提交于 2019-12-06 15:49:55

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.

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