用django通过按回车键将数据添加到数据库中

问题描述:

当我试图将数据添加到数据库时,我看不到我做错了什么。当我按下提交按钮时,数据库中不会输入任何内容。按Enter键时会发生同样的情况。用django通过按回车键将数据添加到数据库中

这是我的html文件。

<script> 
 
    $(document).keypress(function(event) { 
 
    if (event.keyCode == 13 || event.which == 13) { 
 
     alert('enter key is pressed'); 
 
     event.preventDefault(); 
 
    } 
 
    }); 
 
</script>
<div class="col-md-6 col-md-offset-3"> 
 
    <form method="POST" action=""> 
 
    <p> 
 
     {% csrf_token %} 
 
     <input type="hidden" value="{{post.id}}" /> 
 
     <div class="col-xs-16" style="margin: 0; 0;padding: 3%;"> 
 
     <label for="inputsm">Oracle</label> 
 
     <input class="form-control input-md" type="text" value="{{ post }}"> 
 
     <input type="submit" value="Submit" style="display: none" /> {{ form.body }} 
 
     <button type="submit" value="Submit" class="btn btn-success">Submit</button> 
 
    </p> 
 
    </div> 
 
    </form> 
 
</div>
这里是views.py

def post_list(request): 
    posts = Post.objects.all() 
    category = Category.objects.all() 
    context = { 
     'posts':posts, 
     'cat':category, 
    } 
    return render(request, 'journal/post_list.html', context) 

def add_post(request): 
    post = get_object_or_404(Post, pk=pk) 
    if request.method == "POST": 
     form = PostForm(request.POST or None) 
     if form.is_valid(): 
      post = form.save(commit=False) 
      post.save() 
      return redirect('post_details', pk=post.pk) 
      return render(request, 'journal/post_list.html', {'post': post}) 

    else: 
     form = PostForm() 
    context = { 
     "form": form, 
    } 
    return render_to_response('journal/post_list.html', context) 
+0

'后= get_object_or_404(邮政,PK = PK)'什么是PK?这是从哪里来的? – karthikr

是否得到表单提交?如果没有,也许尝试加入一些JavaScript来提交表单,当按键被按下

$("form").submit(); 
+0

添加此代码时,这会变得更好。数据正在输入数据库中。但是,由于数据不显示,我仍然在做错事。它显示为短划线。感谢您的推动。 – Arielis