【发布时间】:2021-07-10 09:00:24
【问题描述】:
我正在使用ajax向我的视图发送数据,目标是在不刷新页面的情况下发布cmets
问题是表单在检查是否有效时总是返回false,我找不到问题希望你能帮助我
当我提交表单时它返回结果:“”因为表单无效
所以我打印了comment_form.errors,看起来数据是空的
<ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li><li>question<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
我的观点
def question_detail(request, slug):
question = get_object_or_404(Question, slug=slug)
allcomments = question.comments.all()
comment_form = CommentCreateForm()
return render(request, 'question/question_detail.html', {'question': question, 'form': comment_form, 'comments': allcomments})
def add_comment(request):
if request.is_ajax() and request.method == 'POST':
comment_form = CommentCreateForm(data=request.POST)
print(comment_form.is_valid())
if comment_form.is_valid():
print('hi')
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('content')
user = request.user
user_comment.author = user
user_comment.save()
return JsonResponse({'result': result, 'user': user.username})
else:
print('anything')
return JsonResponse({"result": ''})
我的模板
<form id="commentform" data-question="{{question.slug}}" class="commentform" method="POST">
<legend class="border-bottom fw-bold">Add a Comment</legend>
{% csrf_token %}
<select name="question" id="id_question" class="d-none">
<option value="{{question.id}}" selected="{{question.id}}"></option>
</select>
<label>{{form.parent.label}}</label>
{{form.parent}}
{{form.content}}
<button type="submit" value="commentform" id="newcomment"
class="newcomment btn btn-primary col-12 mt-1">Post</button>
</form>
$(document).on('click', '#newcomment',' #newcommentinner', function(e){
e.preventDefault();
let button = $(this).attr("value");
// let slug = $('#commentform').attr("data-question")
let csrftoken = $('[name="csrfmiddlewaretoken"]').val();
// let patch = "{% url 'question:question_detail' 0 %}".replace(0, slug)
console.log($("#commentform").serialize())
var placement = "commentform"
if (button == "newcommentform") {
var placement = "newcommentform"
}
$.ajax({
type:'POST',
url:"{% url 'question:add_comment' %}",
data:{
'data': $("#" + button).serialize(),
'csrfmiddlewaretoken': csrftoken,
},
cache:false,
success: function(json) {
console.log(json)
},
error: function(xhr, errmsg, err){
}
})
});
【问题讨论】:
-
视图的默认方法是 get 方法,所以在你的函数中只有当方法是 post 时才返回,所以当你在浏览器中调用这个视图时会返回你得到的错误
-
@DimitrisKougioumtzis 我更新了问题你可以看看
-
当您尝试发布评论时,某些字段为空,并且在评论模型中需要空字段,因此您必须检查发布的数据是否包含模型所需的所有字段
-
@DimitrisKougioumtzis 仅当我将数据发送到视图时数据为空,这就是表单无法验证的原因,但当我 console.log 时它在 ajax 函数中
-
当您单击按钮通过 ajax 函数发布数据时,请检查您发布表单使用的正确数据
标签: django django-views django-forms django-templates