我無法從我的模板傳遞值來查看。基本上,我爲用戶註冊創建了一個表單,並希望將模板中的值傳遞給查看,以便我可以構造一個User對象以添加到我的數據庫中。但不知何故,當我加入name={{user_form.username}}
時,我的「輸入」不起作用。另外,當我選擇「借款人」,「libarrian」和「店員」時,我想分別傳遞值0,1,2,我該如何執行此操作?Django將值從模板傳遞到視圖
以下是我的代碼。
<form id="user_form" method="post" action="/sign_up/" class="form-signin" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">Signup </h2>
{% if error%}
<div class="error"> Your registration has been unsuccessfull </div>
{% endif %}
<input type="text" class="form-control" name="username" value="{{user_form.username}}" placeholder="Username" required autofocus>
<input type="password" class="form-control" name="password1" placeholder="Password" value="" required>
<input type="password" class="form-control" name="password2" placeholder="Retype password" value="" required>
<select class="form-control">
<option value="2">Librarian</option>
<option value="0">Borrower</option>
<option value="1">Clerk</option>
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
</form>
在forms.py
class UserForm(forms.Form):
username = forms.CharField(max_length=30)
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
在views.py
def sign_up(request):
registered = False;
error = False;
if request.method == 'POST':
user_form = UserForm(request.POST)
if user_form.is_valid():
registered = True
username = user_form.cleaned_data['username']
password = user_form.cleaned_data['password']
user = User.objects.create_user(username, None, password)
user.save()
else:
error = True;
else:
user_form = UserForm()
return render(request, 'books/sign_up.html',
{'user_form':user_form,
'registered':registered, 'error':error})
你能提供模板渲染線 - 你如何將表單對象傳遞給模板? – johnbarr
我從來沒有聽說過類型爲「username」的任何「輸入」控件..這是一種類型還是您將其命名爲這樣? – anuragal