【问题标题】:Ajax Post Request isn´t working in djangoAjax 发布请求在 django 中不起作用
【发布时间】:2021-12-21 13:36:09
【问题描述】:

我对 django 有疑问。我对其他问题进行了很多研究,但他们的答案对我不起作用。我需要将图像的 base64 字符串发送到我的视图,以便我可以将字符串而不是图像存储在我的数据库中。所以,我想通过 ajax 将数据发送到我的 django 视图。由于某种原因,表单已经由 django 自动提交,我试图阻止它,但是 ajax 也没有触发。我真的很感激帮助,因为它已经花费了我很多时间。

add.html

<form method="post" enctype="multipart/form-data" onsubmit="submitdata()">
    {% csrf_token %}
    <input type="text" name="dish" required id="id_dish" placeholder="Rezeptname">
    <img ><input type="file" name="image" required id="id_image" accept="image/*">
    <div class="image-upload"><img id="img_id" src="#">
    </div><button type="submit">Upload</button>
</form>
<script>
    function submitdata() {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/add",
        data: JSON.stringify({
           csrfmiddlewaretoken: document.getElementsByName("csrftoken")[0].value,

            "dish": "test",
            "image": dataurl,
            "recipe": document.getElementsByName("recipe")[0].value,
            "caption": document.getElementsByName("caption")[0].value
        }),
        dataType: "json",
    });
}
</script>

views.py

@login_required(login_url="login")
def add(response):
  if response.method == "POST":
    form = AddForm(response.POST, response.FILES)

    if form.is_valid():
        
        print(response.POST)
        # The print statement prints the data from the automatical form 
          submit, not from the ajax submit


        current_user = Client.objects.get(id=response.user.id)
        current_user.post_set.create(poster=response.user.username,
                                    dish=form.cleaned_data.get("dish"),
                                    image=response.POST.get("image"),
                                    caption=form.cleaned_data.get("caption"),
                                    recipe=form.cleaned_data.get("recipe"))
        
        messages.success(response, "You successfully added a post.")
        return redirect("home")

else:
    form = AddForm()

return render(response, "main/add.html", {"form":form})

urls.py

urlpatterns = [
path("add", views.add, name="add")
]

forms.py

class AddForm(forms.ModelForm):

dish = forms.CharField()
image = forms.FileField()
caption = forms.TextInput()
recipe = forms.TextInput()

class Meta:
    model = Post
    fields = ["dish", "image", "recipe", "caption"]

【问题讨论】:

    标签: django ajax django-views django-forms


    【解决方案1】:

    当您使用 onsubmit 属性并希望阻止表单发送数据时,请确保处理程序返回 false。

    如果 onsubmit 处理程序返回 false,则不会提交表单的元素。如果处理程序返回任何其他值或什么都不返回,则表单正常提交。

    <script>
        function submitdata() {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/add",
            data: JSON.stringify({
    
                "dish": "test",
                "image": dataurl,
                "recipe": document.getElementsByName("recipe")[0].value,
                "caption": document.getElementsByName("caption")[0].value
            }),
            dataType: "json",
    
            //return false if ajax is successful
            // you can also do something with response data if needed
            success: function(data) {return false;},
            //return false if ajax request returns error
            error: function(data) {return false;},
        });
    }
    </script>
    

    【讨论】:

    • 试试这个,当我点击按钮时表单正在提交,但再次没有 ajax 帖子。
    • @Moritz_1201:这是因为 ajax 请求可能返回错误。以类似的方式,您可以添加错误:function(data) {return false;}。这将在任何情况下阻止表单表单提交。但是你需要处理你的错误。
    • 我试图 console.log 错误,它说“Uncaught TypeError: Cannot read properties of undefined (reading 'value')”(编辑:它与 csrfmiddlewaretoken 有关,所以现在出现错误不再存在,但仍然无法正常工作)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多