【发布时间】: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