Reputation: 317
I'm having trouble passing values from my template to view. Basically I created a form for user registration, and want to pass the values from the template to view so that I can construct a User object to add to my database. But somehow my "input" is not working when I add name={{user_form.username}}
. Also, I want to pass values 0,1,2 respectively when I select "borrower", "libarrian" and "clerk", what can I do to implement this?
Below are my codes.
<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>
In forms.py
class UserForm(forms.Form):
username = forms.CharField(max_length=30)
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
In 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})
Upvotes: 0
Views: 1492
Reputation: 3114
Below form should work.
<form id="user_form" method="post" action="/sign_up/" class="form-signin" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">Signup </h2>
<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" required>
<input type="password" class="form-control" name="password2" placeholder="Retype password" required>
<select class="form-control">
<option value="1">Librarian</option>
<option value="0">Borrower</option>
<option value="2">Clerk</option>
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
</form>
Changes I have done are -
Upvotes: 1