我在Django
中更新,前段时间我完全坚持我的请求问题。我试图从POST
表单中Django
。我使用json
和AJAX
执行此操作
这是我的代码
form.py
class PostForm(forms.ModelForm):
class Meta:
model = Message
fields = ['message_text']
widgets = {
'message_text': forms.TextInput(
attrs={'id': 'message_text', 'required': True,
'placeholder': 'new message...', }),}
views.py
def index(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.cleaned_data
message_t = request.POST.get('message_text')
response_data = {}
new_mess = Message(message_text = message_t,
post_time = message_t.created,
username="second")
new_mess.save()
response_data['result'] = message_t
else:
response_data['result'] = 'nothing...'
else:
form = PostForm()
template = loader.get_template('chat/index.html')
context = RequestContext(request, {
'form': form, })
return HttpResponse(template.render(context))
(在views.py的另一个变体中,我尝试将POST请求处理与另一个函数分开,但它也不起作用)
HTML:
<form method="POST" id="post-form">
<td class="col-lg-6"><div class="fieldWrapper" id="the_post"
class="form-control" type="text">
{{ form.message_text }}
</div></td>
<td class="col-lg-6"> <input type="submit" value="Post"
class="btn btn-success" name = "Post"></td>
</form>
JS:
$(function() {
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
create_post();
});
function create_post() {
console.log("create post is working!") // sanity check
$.ajax({
url : "/chat/new_message/", // the endpoint
type : "POST", // http method
data : { the_post : $('#post-form').val() },
success : function(json) {
$('#post-form').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
console.log("success");
},
error : function(xhr,errmsg,err) {
...
}
});
};
});
在结果中POST
成功,没有出现错误,但基础中也没有创建记录。
注意:此外,我已将csrf
排除在外
有人可以帮助我找出错误吗?
答案 0 :(得分:1)
表单无效。它永远不会有效,因为你发送了一个带有表单数据的JSON字典,其中包含键#34; the_post&#34;,但你还没有告诉视图看那里。
视图无法报告表单的状态,因为您构建了一个响应 - &#34; response_data&#34; - 然后忽略它。
最后,你的视图不会发送回JSON - 它会发送回渲染的模板,好像它是一个普通的非Ajax视图 - 所以接收JS不知道如何处理它。
答案 1 :(得分:0)
我找到了POST的修复程序。 主要的问题是在json体中,我使用了错误的值名称,它必须是:
data : { the_post : $('#message_text').val() },
现在请求不为空。