form.is_valid():始终返回false

时间:2014-10-31 10:17:07

标签: python django image forms

Form.is_valid()始终返回false。这是我的代码。

#urls.py
url(r'^create/', "app.views.createpost", name="createpost"),

我的models.py

class Post(models.Model):
    """docstring for Post"""
    post_image = AjaxImageField(upload_to='posts', max_width=200, max_height=200, crop=True, null= False, default='site_media/media/BobMarley/bob1.jpg')
    poster = models.ForeignKey(User, null= False, default=User.objects.get(username="admin")

这是我的forms.py

#forms.py
class AjaxImageUploadForm(forms.Form):
    image = forms.URLField(widget=AjaxImageWidget(upload_to='posts'))    

view.py

#views.py
def createpost(request):

    if request.method == 'POST':
        form = AjaxImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            newpost = Post(post_image = request.FILES['image'])
            newpost.poster = request.user
            newpost.save()

            return HttpResponseRedirect('/create/')


    else:
        form = AjaxImageUploadForm() # An empty, unbound form


    posts = Post.objects.all()

    return render_to_response('create.html',{'posts': posts, 'form': form},context_instance=RequestContext(request))

模板

#create.html
{% block extra_head %}    
    {{ form.media }}
{% endblock %}
{% block body %}
    <form method="POST" enctype="multipart/form-data" action="{% url "createpost" %}">      
        {% csrf_token %} 
        {{ form.errors}}
        {{ form.as_p }}
        <button type="submit" name='image'>Upload</button>
    </form>   
{% endblock %}

表单永远无效,打印错误为“此字段为必填项”。 这是表单小部件开始创建

<tr><th><label for="id_image">Image:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul>
<div class="ajaximage"><a class="file-link" target="_blank" href=""> <img class="file-img" src=""></a> <a class="file-remove" href="#remove">Remove</a>
<input class="file-path" type="hidden" value="" id="id_image" name="image" /> <input type="file" class="file-input" name="image"/> <input class="file-dest" type="hidden" name="image" value="/ajaximage/upload/posts/0/0/0"> <div class="progress progress-striped active"> <div class="bar"></div></div>    
</div>
</td></tr>

我正在使用名为django-ajaximage的django包,他们的自定义小部件(AjaxImageWidget)可能是一个自定义文本小部件

class AjaxImageWidget(widgets.TextInput):

谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

您的模型类不需要 init 。此外,null = False是默认值。我不确定文本“admin”会默认使用用户名admin的用户。你需要这样做:

default=User.objects.get(username="admin")

您还可以在创建对象时包含海报分配,如下所示:

newpost = Post(post_image=request.FILES['image'], poster=request.user)

要使表单验证,您需要在字段中输入blank = True,如下所示:

poster = models.ForeignKey(User, blank=True, default=User.objects.get(username="admin")

我还要将表单设为ModelForm:

class AjaxImageUploadForm(forms.ModelForm):
    class Meta:
        model=Post
        exclude=['poster',]