Ajax Post Request 在 django 中不起作用



我对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>

视图.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")
]

表单.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"]

当您使用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>

最新更新