【问题标题】:How to save a string variable from views in Django如何从Django中的视图中保存字符串变量
【发布时间】:2019-07-04 15:59:59
【问题描述】:

我正在尝试将 pytesseract 用于我的 Django 应用程序。在 views.py 中,我调用了 pytesseract 并将它找到的所有文本存储在“text_content”变量中。我想将此变量保存为我的模型的“文本”参数,但我不知道如何去做。

我尝试使用 .save(),但收到此错误:

'str' 对象没有属性'save'

这里是views.py

def image_view(request):
    if request.method == 'POST':
        form = partForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            data = request.POST.copy() 
            image_file = request.FILES.get('image')
            text_content = pytesseract.image_to_string(Image.open(image_file))
            text_content.save()
            return redirect('success')
    else:
        form = partForm()
    return render(request, 'add_image.html', {'form' : form})

这里是models.py

class Component(models.Model):
    snum = models.CharField(max_length=20, default = '')
    image = models.ImageField(blank=True)
    text = models.TextField(default = 'no text found')

这是forms.py

class partForm(forms.ModelForm):
    snum = forms.CharField(max_length=128, help_text="please enter the 
    number.")

   class Meta:
        model = Component
        fields = ['snum', 'image']

【问题讨论】:

    标签: python django ocr


    【解决方案1】:

    由于这一行而发生错误。 text_content.save()

    您正在尝试对字符串对象调用保存函数。

    现在要解决您的问题,有两种方法可以解决。一种是操作请求数据并将其发送到表单,另一种是在模型的保存方法中进行。

    方式 1:在您当前的视图中

    if form.is_valid():
        data = request.POST.copy()
        image_file = request.FILES.get('image')
        text_content = pytesseract.image_to_string(Image.open(image_file))
        data['relevant_field_name'] = text_content
        new_form = partForm(data) 
        if new_form.is_valid():
            new_form.save() 
    return redirect('success')
    

    方式2:在models.py中,将这个添加到Component

    def save(self, *args, **kwargs):
        if getattr(self, 'image'): 
              image_file = self.image
              self.relevant_field_name = pytesseract.image_to_string(Image.open(image_file))
        super(Component, self).save(*args, **kwargs)
    

    【讨论】:

    • 我尝试了第一种方法,现在可以了!非常感谢!!
    猜你喜欢
    • 2021-05-17
    • 2020-10-21
    • 1970-01-01
    • 2016-12-31
    • 2019-08-19
    • 2015-07-07
    • 2013-04-13
    • 2016-08-24
    • 2016-05-09
    相关资源
    最近更新 更多