我目前正在學習Django,並且想知道我是否正確理解了所有這些。在我的views.py中,我用args={}
創建了一個args字典。我通過args.update(csrf(request))
和args['form'] = MyRegistrationForm()
將2個值傳入args
。我想知道return render(request, 'register.html', args)
這行,我是從args['form']
的空白表單傳入HTML頁面,標記爲{{form}}
?將表單傳遞給HTML頁面django
我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 %}
我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
你試過'{{form.as_p}}'? – lalo
不,我沒有!這到底做了什麼? – Liondancer
它會打印出來的表格字段 – lalo