Initial populating on Django Forms

S. Lott’s answer tells you how to initialize the form with some data in your view. To render your form in a template, see the following section of the django docs which contain a number of examples:

Although the examples show the rendering working from a python interpreter, it’s the same thing when performed in a template.

For example, instead of print f, your template would simply contain: {{ f }} assuming you pass your form through the context as f. Similarly, f.as_p() is written in the template as {{ f.as_p }}. This is described in the django template docs under the Variables section.

Update (responding to the comments)

Not exactly, the template notation is only for template. Your form and associated data are initialized in the view.

So, using your example, your view would contain something like:

def view(request):
    game = Game.objects.get(id=1) # just an example
    data = {'id': game.id, 'position': game.position}
    form = UserQueueForm(initial=data)
    return render_to_response('my_template.html', {'form': form})

Then your template would have something like:

{{ form }}

Or if you wanted to customize the HTML yourself:

{{ form.title }} <br />
{{ form.genre }} <br />

and so on.

I recommend trying it and experimenting a little. Then ask a question if you encounter a problem.

Leave a Comment