Django版本1.11.1
我在<form action="" class="poster" id="posterForm">
{% csrf_token %}
<input type="file" accept="image/png,image/gif,image/jpeg" id="img_input" class="file_btn">
<input type="button" class="file_front_btn" value="选择图片" name="image">
<input type="text" name="title" id="title" class="title_area" placeholder="标题(不超过20字):">
<span class="img_root">已选图片:<span id="img_root" class="hidden">无</span></span>
<textarea name="content" id="content" name="content" class="content_area" placeholder="输入内容(不超过2000字):"></textarea>
<div id="title_error"></div>
<div id="content_error"></div>
<input type="button" class="submit" id="submitBtn" value="发布">
<div id="img_error"></div>
</form>
上有一个表单,想用ajax发布它只能更改表单,我的表单代码如下:
jQuery
我的$(function(){
$('#submitBtn').on('click', function(){
$.ajax({
cache: false,
type: "POST",
url:"{% url 'community:poster' %}",
data:$('#posterForm').serialize(),
async: true,
success: function(data) {
if(data.status == 'success'){
$('#posterForm')[0].reset();
alert("发布成功")
}else if(data.status == 'fail'){
$('#img_error').html(data.msg)
}
},
});
});
})
:
views
我的class PosterView(View):
def post(self, request):
poster_form = PostForm(request.POST)
if poster_form.is_valid():
poster = poster_form.save(commit=True)
return HttpResponse("{'status':'success'}", content_type='application/json')
else:
return HttpResponse("{'status':'fail', 'msg':{0}}".format(poster_form.errors), content_type='application/json')
是:
ModelForm
我使用class PostForm(forms.ModelForm):
class Meta:
model = Posts
fields = ['image', 'title', 'content']
提交表单,表单为:
urlpatterns =[
url(r'^allpost/$', AllPosts.as_view(), name='allpost'),
url(r'^poster/$', PosterView.as_view(), name='poster'),
网址:
{{1}}
我无法查看问题所在,但是当我点击提交按钮时,没有任何反应,没有失败状态。