简体   繁体   English

如何使用 Django 将表单中的数据发布/删除到数据库中?

[英]How to post/delete data from form into database using Django?

I am using a form to post a record to my database in Django.我正在使用表格将记录发布到 Django 中的数据库。 The form looks something like this:表单看起来像这样:

<form>
    <div>Field 1</div>
    <input/>
    <div>Field 2</div>
    <input/>
    ...
    <a id='save'>Save</a>
</form>

I am using an event listener to let me know when this Save link has been clicked.我正在使用事件侦听器让我知道何时单击了此保存链接。 When it is clicked, I would like to store the fields as a record in the database.单击它时,我想将字段作为记录存储在数据库中。

Here is my JS:这是我的 JS:

const savebtn = document.querySelector('#save');
savebtn.addEventListener('click', showSelected);

function showSelected(e) {
    // post record to database here
    window.location.replace("/"); // redirect to home page

I am hoping to use some python to post this record like shown below:我希望使用一些 python 来发布这条记录,如下所示:

e = Entry()
e.field1 = 1
e.field2 = 2
e.save()

But I don't know how I can access a python function within JS.但我不知道如何在 JS 中访问 python function。 I'm thinking maybe a template tag could work here but can't figure out how to use it.我在想也许模板标签可以在这里工作,但不知道如何使用它。 Ideally I wouldn't have to rewrite the form as the formatting is kind of specific, is there a way to make this work?理想情况下,我不必重写表单,因为格式是特定的,有没有办法让它工作?

You have to create an endpoint that will do the algorithm.您必须创建一个执行算法的端点。

ie. IE。 some urls.py:一些urls.py:

urlpatterns = [
    path('my_save_view', my_save_view, ...),
    ]

views.py:视图.py:

def my_save_view(request):
    e = Entry()
    e.field1 = 1
    e.field2 = 2
    e.save()

and in javascript just get/fetch that endpoint when you want to.并且在 javascript 中,只需在需要时获取/获取该端点。 You can pass any values to the view with either GET or POST method in a standard way if needed.如果需要,您可以使用 GET 或 POST 方法以标准方式将任何值传递给视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM