在Django中提交帖子表单时出现值错误

时间:2017-02-08 09:16:20

标签: python django forms

我正在尝试为我正在构建的基于Django的Web应用程序制作提交表单。但是,当我按提交时,我收到此错误:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/create

Django Version: 1.10.5
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'posts',
 'bootstrap3']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/wtreston/GDrive/Django/blog/posts/views.py" in post_create
  15.         instance = form.save(commit=False)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/models.py" in save
  448.                     'created' if self.instance._state.adding else 'changed',

Exception Type: ValueError at /create
Exception Value: The Post could not be created because the data didn't validate.

这是我创建表单的html文件:

{% extends "base.html" %}


{% block title %}Create new Post | {{ block.super}}{% endblock title %}

{% block content %}

<h1>Create Post</h1>

<form method = 'POST' action = '' class = 'form'>{% csrf_token %}
  <div class="form-group">
    <label for="post_title">Post Title</label>
    <input  class="form-control" id="post_title" placeholder="Post Title">
  </div>
  <div class="form-group">
    <label for="post_content">Post Content</label>
    <textarea class="form-control" rows="6" placeholder="Post Content"></textarea>
  </div>
  <!--<div class="form-group">
    <label for="exampleInputFile">File input</label>
    <input type="file" id="exampleInputFile">
  </div>-->

  <button type="submit" name="your_name" value="your_value" class="btn-link">Go</button>


</form>


{% endblock content %} %}

这是我在views.py中的创建视图:

def post_create(request):
    if not request.user.is_authenticated:
        return(redirect("posts:post_timeline"))

    form = PostForm(request.POST or None)
    if form.is_valid and request.POST:
        instance = form.save(commit=False)
        instance.save()
        return(HttpResponseRedirect(instance.get_absolute_url()))

    context = {
        "form": form,
    }

    return render(request, "post_form.html", context)

关于为什么会发生这种情况的任何想法?

非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助: -

from .forms import YourFormClass

def post_create(request):
    if not request.user.is_authenticated:#If this condition is without checking POST request
        return(redirect("posts:post_timeline"))

    if request.method == 'POST':
        form = YourFormClass(request.POST)

        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            return(HttpResponseRedirect(instance.get_absolute_url()))

        else:
             #Do something
             #OR
             form = YourFormClass()


    context = {
        "form": form,
    }

    return render(request, "post_form.html", context)