Django将值从模板传递到视图

时间:2014-03-25 05:29:21

标签: python django web

我无法将模板中的值传递给查看。基本上我创建了一个用户注册表单,并希望将模板中的值传递给视图,这样我就可以构造一个User对象来添加到我的数据库中。但是当我添加name={{user_form.username}}时,我的“输入”无法正常工作。另外,当我选择“borrower”,“libarrian”和“clerk”时,我想分别传递值0,1,2,我该怎么做才能实现它?

以下是我的代码。

      <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})

1 个答案:

答案 0 :(得分:1)

下面的表格应该有用。

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

我所做的改变是 -

  1. 更改用户名和密码文本框的名称
  2. 更改用户名文本框的类型
  3. 在选择控件中添加值属性