Skip to main content
 首页 » 编程设计

python之Django 中的请求

2025年05月04日48zhujiabin

我是 Django 的新手,不久前我完全陷入了我的请求问题。我正在尝试从 Django 表单执行 POST。我使用 json 和 AJAX 来做到这一点 这是我的代码

表单.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...', }),} 

View .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 everywere

谁能帮我找出问题所在?

请您参考如下方法:

表格无效。它永远不会有效,因为您正在发送一个 JSON 字典,其中包含键“the_post”中的表单数据,但您没有告诉 View 查看那里。

并且 View 无法报告表单的状态,因为您构造了一个响应 - “response_data” - 然后忽略了它。

最后,您的 View 无论如何都不会发回 JSON - 它会发回呈现的模板,就好像它是一个普通的非 Ajax View 一样 - 所以接收 JS 不知道如何处理它。