Reputation: 16469
I am currently learning Django and I was wondering if I am understanding all of this correctly. In my views.py, i created an args dictionary with args={}
. I passed in 2 values into args
with args.update(csrf(request))
and args['form'] = MyRegistrationForm()
. I was wondering in the line return render(request, 'register.html', args)
, am I passing in an empty form from args['form']
into the HTML page where it is labeled {{form}}
?
my register.html:
{% extends 'base.html' %}
{% block content %}
<h2>Register</h2>
<form action = '/accounts/register/' method = 'POST'>{% csrf_token %}
{{form}}
<input type = 'submit' value = "Register" />
</form>
{% endblock %}
my views.py:
def register_user(request):
# second time around
if request.method == 'POST': # look into request.method and see if it has POST
form = MyRegistrationForm(request.POST) # pass through the values in the POST to the custom form to create form object
if form.is_valid(): # check if information if correct
form.save() # if correct, save form, and that will save the registration information for the new user
return HttpResponseRedirect('/accounts/register_success')
# first time around
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm() # BLANK user creation form with no information
return render(request, 'register.html', args) # passes 'form' from args into the html page
Upvotes: 1
Views: 141
Reputation: 625
Yes, args is set to a instance of your form MyRegistrationForm as form.
This is beyond what you have asked but I have recently used. if you want to customise your HTML further for the form you can use a for loop to loop through your form displaying labels and input fields corresponding to your model.
example below - using styled twitter bootstrap
<form class="form-horizontal" action="/accounts/register/" method="post">{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label for="id_{{ field.name }}" class="col-sm-2 control-label">{{ field.label }}</label>
<div class="col-sm-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
field.label - label
field - input field
Upvotes: 1
Reputation: 53326
am I passing in an empty form from
args['form']
into the HTML page where it is labeled{{form}}
Yes.
Upvotes: 1