Django可以打开图像,但不能将其保存到数据库

时间:2019-07-10 20:00:09

标签: python django ocr

我创建了一个表单,该表单将要求在django中上传名称和图像。在我看来,我正在使用pytesseract来读取图像上的文本。我能够成功将名称和文本参数保存到数据库中,但是图像本身无法保存。

`# models.py 
class Component(models.Model):
    Serial_number = models.CharField(max_length=20, primary_key='True', default = '')
    image = models.ImageField(blank=True)
    text = models.TextField(default = 'no text found')
    Good_Candidate = models.BooleanField(default=False)
    dimension1 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)


#forms.py
class partForm(forms.ModelForm):
    Serial_number = forms.CharField(max_length=128)

class Meta:
    model = Component
    fields = ['Serial_number', 'image', 'text', 'dimension1']
    widgets = {'dimension1': forms.HiddenInput(), 'text':forms.HiddenInput()}

#views.py
def image_view(request):
    form = partForm(request.POST, request.FILES)

    if form.is_valid():
        # make copy of the data
        data = request.POST.copy()
        # access image data through FILES and calling the name attribute
        image_file = request.FILES.get('image')
        text_content = pytesseract.image_to_string(Image.open(image_file))
        data['text'] = text_content
        # get largest dimension
        text_list = []
        zeros = ['O', 'o']
        badChars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
        'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'z', '—', '——', '-', '+', ':', '\'', '‘', '’', '$', ',', '¢', '/']
        decimals = ['_']
        for letter in badChars:
            text_content = text_content.replace(letter, " ")
        for letter in zeros:
            text_content = text_content.replace(letter, "0")
        for letter in decimals:
            text_content = text_content.replace(letter, ".")

        text_list = text_content.split()

        # remove all non digits from list
        new_list = []
        for i in range(0, len(text_list)):
            if text_list[i].isdigit():
                new_list.append(int(float(text_list[i])))

        data['dimension1'] = max(new_list)

        # save fields to form
        new_form = partForm(data)
        if new_form.is_valid:
            new_form.save()
        return redirect('success')

1 个答案:

答案 0 :(得分:0)

为什么不呢?

setTimeout()

我想念什么吗?