H_MZ 2015-10-01 20:45 采纳率: 0%
浏览 37

Django中的请求

I'm newer in Django and some time ago I've totally stuck on problems with my requests. I'm trying to do POST from Django form. I do that with json and AJAX Here is my code

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))

(In another variant of views.py I tried to separate POST request handling to another function, but it doesn't work as well)

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) {
           ...
        }
            });
        };
    });

In the result my POST is successful, no error appears, but no record in the base created too. Note: Also I've excluded csrf everywere

Can someone help me to figure out what's wrong?

  • 写回答

2条回答 默认 最新

  • weixin_33744141 2015-10-01 21:15
    关注

    The form is not valid. It can never be valid, because you are sending a JSON dictionary with the form data inside the key "the_post", but you haven't told the view to look there.

    And the view can't report back the status of the form, because you construct a response - "response_data" - and then ignore it.

    Finally, your view does not send back JSON anyway - it sends back the rendered template, as if it were a normal non-Ajax view - so the receiving JS has no idea what to do with it.

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程