Django:如何在表单旁边添加错误消息

时间:2014-03-26 04:41:36

标签: django web

目前我有一张表格,但无论怎么注册,我都会失败。我的实现没有显示什么是错的。有人能弄明白可能会发生什么吗?

另外,如何在每个输入框旁边添加错误消息?

以下是我的代码

    {% block content%}


     <div class="container">

      <form class="form-signin" method="post" action="/sign_in/" role="form">
        {% csrf_token %}
        <h2 class="form-signin-heading">Please sign in</h2>
        {% if error%} Your registration has not been successful. {%endif%}
        <input type="username" class="form-control" name="username" placeholder="Username" required>
        <input type="password" class="form-control" name="password" placeholder="Password" required>
        <input type="password" class="form-control" name="password2" placeholder="Password" required>
        <input type="username" class="form-control" name="name" placeholder="Name" required>
        <input type="username" class="form-control" name="address" placeholder="Address" required>
        <input type="username" class="form-control" name="Phone" placeholder="Phone Number" required>
        <input type="email" class="form-control" name="emailAddress" placeholder="Email" required>
        <input type="sinOrStNo" class="form-control" name="sinOrStNo" placeholder="Username" required>

        <select class="form-control" name="type">
  <option value="ST">Student</option>
  <option value="FA">Faculty</option>
  <option value="SF">Staff</option>
</select>

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>

    </div> <!-- /container -->

{% endblock %}

my views.py

 error = False;
    if request.method == 'POST':
        borrower = BorrowerForm(request.POST)
        if borrower.is_valid():
            username = borrower.cleaned_data['username']
            password = borrower.cleaned_data['password']
            type = borrower.cleaned_data['type']
            name = borrower.cleaned_data['name']
            address = borrower.cleaned_data['address']
            phone = borrower.cleaned_data['phone']
            emailAddress = borrower.cleaned_data['emailAddress']
            sinOrStNo = borrower.cleaned_data['sinOrStNo']
            expiryDate = borrower.cleaned_data['expiryDate']

            # add borrower accounts
            user = User.objects.create_user(username, None, password)
            user.set_password(password)
            user.save()
            user_type = UserProfile(username=username,type=0)
            user_type.save()

            # add borrower table
            borrower_user = Borrower(username = username, password=password,name= name, address=address, phone=phone,emailAddress=emailAddress,sinOrStNo=sinOrStNo, expiryDate=expiryDate, type=type)
            borrower_user.save()
        else:
            error = True;

    else:
        borrower = BorrowerForm()

    return render(request, 'books/clerk/add_borrower.html', {'logged_in':logged_in, 'username':username, 'type':type, 'error':error, 'borrower':borrower})

我的forms.py

 class BorrowerForm(forms.Form):
        username = forms.CharField(max_length=30)
        password = forms.CharField(widget=forms.PasswordInput())
        password2 = forms.CharField(widget=forms.PasswordInput())
        name = forms.CharField(max_length=30)
        address = forms.CharField(max_length=30)
        phone = forms.CharField(max_length=30)
        emailAddress = forms.CharField(widget=forms.EmailInput())
        sinOrStNo = forms.CharField(max_length=10)
        expiryDate = forms.DateField()
        type = forms.CharField(max_length=3)

        def clean_username(self):
            existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
            if existing.exists():
                raise forms.ValidationError(("A user with that username already exists."))
            else:
                return self.cleaned_data['username']

        def clean(self):
            if 'password' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password'] != self.cleaned_data['password2']:
                    raise forms.ValidationError(("The two password fields didn't match."))
            return self.cleaned_data

1 个答案:

答案 0 :(得分:1)

你使用表单并在html文件中写下所有htmls为什么???

为什么不使用

views.py

if request.method=='POST':
    borrower = BorrowerForm(request.POST)
    if borrower.is_valid():
        ......
        return HttpResponseRedirect(<success url>)
    else:
        #here error messages it passed along with the form
        return render(request, 'books/clerk/add_borrower.html',
            {'borrower':borrower})

borrower = BorrowerForm()
return render(request, 'books/clerk/add_borrower.html',
   {'logged_in':logged_in, 'username':username, 'type':type, 
   'error':error, 'borrower':borrower})

并使用模板。这就是forms.py的目的。喜欢:

<form class="form-signin" method="post" action="/sign_in/" role="form">
    {% csrf_token %}
    {{borrower.as_table}}
</form>