2013-11-25 136 views
1

我目前正在學習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 
+0

你試過'{{form.as_p}}'? – lalo

+0

不,我沒有!這到底做了什麼? – Liondancer

+0

它會打印出來的表格字段 – lalo

回答

1

我在一個空的形式傳遞從args['form']進入它標記爲{{form}}

是HTML頁面。

1

看到這個docs。和嘗試:

{% extends 'base.html' %} 

{% block content %} 

    <h2>Register</h2> 
    <form action = '/accounts/register/' method = 'POST'> 
    {% csrf_token %} 
    {{form.as_p}} 
    <input type = 'submit' value = "Register" /> 
    </form> 

{% endblock %} 
1

是的,args被設置爲您窗體MyRegistrationForm的一個實例作爲窗體。

這超出了你所問,但我最近使用過。如果要爲表單自定義HTML,可以使用for循環來循環顯示與您的模型對應的標籤和輸入字段。下面

例子 - 使用風格的Twitter的引導

<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 - 標籤

場 - 輸入字段

+0

我給它一個鏡頭謝謝你!花了一點點讓我想出這是如何完成的!感謝您的幫助!非常感激! – Liondancer