将JavaScript生成的图像发送到Django ModelForm时出错

2024-10-03 21:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用https://github.com/szimek/signature_pad将签名附加到表单并发送到服务器。我已经能够使用标准的ImageField成功地上传图像,并且还使用szimek/signature_pad下载签名。但是,当我尝试将签名发送到服务器时,我得到了“(隐藏字段签名)没有提交任何文件。请检查表单上的编码类型。”因此,我认为我至少成功地将图像发送到了字段,但不确定如何对其进行编码

HTML

<form id="form" action="{% url ‘my_app:testFormPage' %}" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  {{ form.as_p }}
  <div id="signature-pad">
    <canvas></canvas><br>
  </div>
  <input type="hidden" name="signature" value=“signatureImage”>
  <button type="submit" data-action="formSig">Submit</button>
</form>

Python

# Models.py
class testModel(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateTimeField(default=timezone.now)
    signature = models.ImageField (null=True, max_length=3000)

# Forms.py
class testForm(forms.ModelForm):
    class Meta:
        model = testModel
        fields = ‘__all__’
        widgets = { 'signature': forms.HiddenInput(),}

# Views.py
def testFormPage(request):
    if request.method == 'POST':
        form = testForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/thanks/')
    else:
        form = testForm()

    context = {'form': form}
    return render(request, 'client_visits/testFormPage.html', context)

Javascript

完整的javascript应用程序可以在https://github.com/szimek/signature_pad/tree/master/docs/js找到。这就是我补充的

var formSig = wrapper.querySelector("[data-action=formSig]");

formSig.addEventListener("submit", function (event) {
        var signatureImage = signaturePad.toDataURL();
    });

Tags: pyhttpsformgithubdatamodelsrequestaction