表格验证中的问题

时间:2018-05-02 18:05:45

标签: python django

我想使用表单验证来验证我的update form。当我将一个字段留空并点击update按钮时,我会看到一个显示错误消息的空白页面。我希望当我将其留空并点击更新按钮时,该错误消息将显示在该特定字段的顶部。

这是我最新的update观点:

def update(request, id):
    item = get_object_or_404(BookEntry, id=id)
    if request.method == "POST":
        form = UpdateForm(request.POST, instance=item)
        # print template
        error_messages = {
            'error': form.errors,
        }
        if form.is_valid():
            print(form.cleaned_data)
            post = form.save(commit=False)
            post.save()
            return HttpResponseRedirect(reverse('bms:index'), id)
        else:
            form = UpdateForm()
            return HttpResponse(json.dumps(error_messages))
    return render(request, 'index.html',{'form':form})

这是我以前的update视图:

def update(request, id):
    item = get_object_or_404(BookEntry, id=id)
    if request.method=="POST":
        form = UpdateForm(request.POST, instance=item)
        if form.is_valid():
            post=form.save(commit=False)
            post.save()
            return HttpResponseRedirect(reverse('bms:index'), id)
        else:
            form=UpdateForm(instance=item)
            return HttpResponseRedirect(reverse('bms:index'), id)
        return render(request, 'bms.html',{'form':form})

这是我的forms.py

class UpdateForm(forms.ModelForm):
    title = forms.CharField(max_length=100)
    author = forms.CharField(max_length=100)
    edition = forms.CharField(max_length=100)
    publisher = forms.CharField(max_length=100)
    genre = forms.CharField(max_length=100)
    detail = forms.CharField(max_length=100)
    language = forms.CharField(max_length=100)
    price = forms.IntegerField()
    dop = forms.CharField(max_length=100)
    cop = forms.CharField(max_length=100)
    copyright = forms.CharField(max_length=100)
    isbn = forms.IntegerField()

    class Meta:
        model = BookEntry
        fields = '__all__'

这是我的html表单:

<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
  {% csrf_token%}
  <div class = "form-group">
    <label for = "title">
      Title:
    </label>
    <input class = "form-control" id="book_title" type = "text" name="title" value="{{ book.title }}">
  </div>
  <div class="form-group">
    <label for = "author">
      Author:
    </label>
    <input id="book_author" class = 'form-control' type = "text" name="author" value="{{ book.author }}">
  </div>
  <div class = "form-group">
    <label for = "edition">
      Edition:
    </label>
    <input id="book_edition" type = "text" class = 'form-control' name="edition" value="{{ book.edition }}">
  </div>
  <div class = "form-group">
    <label for ="publisher">
      Publisher:
    </label>
    <input id="book_publisher" type = "text" name="publisher" class = 'form-control' value="{{ book.publisher }}"/>
  </div>
  <div class = "form-group">
    <label for ="genre">
      Genre:
    </label>
    <input id="book_genre" type = "text" name="genre" class = 'form-control' value="{{ book.genre }}"/>
  </div>
  <div class = "form-group">
    <label for ="detail">
      Detail:
    </label>
    <input id="book_detail" type = "text" name="detail" class = 'form-control' value="{{ book.detail }}"/>
  </div>
  <div class = "form-group">
    <label for ="language">
      Language:
    </label>
    <input id="book_language" type = "text" name="language" class = 'form-control' value="{{ book.language }}"/>
  </div>
  <div class = "form-group">
    <label for ="price">
      Price:
    </label>
    <input id="book_price" type = "text" name="price" class = 'form-control' value="{{ book.price }}"/>
  </div>
  <div class = "form-group">
    <label for ="dop">
      DOP:
    </label>
    <input id="book_dop" type = "text" name="dop" class = 'form-control' value="{{ book.dop }}"/>
  </div>
  <div class = "form-group">
    <label for ="cop">
      COP:
    </label>
    <input id="book_cop" type = "text" name="cop" class = 'form-control' value="{{ book.cop }}"/>
  </div>
  <div class = "form-group">
    <label for ="cop">
      Copyright
    </label>
    <input id="book_copyright" type = "text" name="copyright" class = 'form-control' value="{{ book.copyright }}"/>
  </div>
  <div class = "form-group">
    <label for ="isbn">
      ISBN:
    </label>
    <input id="book_isbn" type = "text" name="isbn" class = 'form-control' value="{{ book.isbn }}"/>
  </div>
  <input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>

这是一个字段留空时显示的URL

http://127.0.0.1:8000/bms/update/2/

这是错误消息:

{"error": {"edition": ["This field is required."]}}

我已将edition字段留空,以检查验证是否正常运行。

有谁能建议我如何以正确的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

丹尼尔指出,你需要重新渲染表格。

HTTP Form Post的基础知识是: 如果表单有效:保存+执行HttpResponseRedirect 如果表格无效;使用错误重新渲染相同的模板

将您的功能更改为:

def update(request, id):
    item = get_object_or_404(BookEntry, id=id)
    if request.method == "POST":
        form = UpdateForm(request.POST, instance=item)
        # print template
        error_messages = {
            'error': form.errors,
        }
        if form.is_valid():
            print(form.cleaned_data)
            post = form.save(commit=False)
            post.save()
            return HttpResponseRedirect(reverse('bms:index'), id)
        return render(request, 'index.html',{'form':form})  # Form invalid case is handled here; the form is reused from above; form.errors is available in the template now
    else:
        pass # Handle GET requests here