Home > Back-end >  request.POST.get didn't get the input value
request.POST.get didn't get the input value

Time:10-21

So, what I was trying to do is that user input a base64 encoded image and than convert it to text via pytesseract OCR. The problem is every time I tried to input it only reload the page and nothing happens.

Here's my html snippet :

<form method="POST" action="{% url 'ocr-view'%}"> {% csrf_token %}
        <label for="base64"> Input Base64 :</label>
        <input type="text" class="form-control" id="text" name="base64" />
        <button type="submit" class="btn btn-primary mt-3" name="submit">
        <i class="fas fa-search"></i>
           Submit
        </button>
</form>


<div class="card-body">
     <label> Result : </label> <br>
     <span class="h3">{{text}}</span>
</div>

Here's my views.py :

class IndexView(LoginRequiredMixin, CreateView):
    model = Ocr
    template_name = "ocr/ocr.html"
    fields = ['input']


    def get_context_data (self):
        text = ""
        
        if self.request.method == 'POST':
            imgstring = self.request.POST.get('base64')
            imgstring = imgstring.split('base64,')[-1].strip()
            image_string = BytesIO(base64.b64decode(imgstring))
            image = Image.open(image_string)

            text = pytesseract.image_to_string(image)
            text = text.encode("ascii", "ignore")
            text = text.decode()

        context = {
            'text': text,
        }
        return context

Urls.py :

from django.urls import path
from .views import IndexView

urlpatterns = [
  path("", IndexView.as_view(), name="ocr-view"),
  path('<int:pk>/', IndexView.as_view(), name='ocr-input'),
]

But if i put the base64 code directly to views.py the OCR function work perfectly.

imgstring = 'data:image/jpeg;base64,/9j/somerandomcode'
imgstring = imgstring.split('base64,')[-1].strip()
image_string = BytesIO(base64.b64decode(imgstring))
image = Image.open(image_string)

text = pytesseract.image_to_string(image)
text = text.encode("ascii", "ignore")
text = text.decode()

context = {
    'text': text,
}
return context

I assume there is something wrong with my post method, please review my code is there anything wrong

CodePudding user response:

I don't think that get_context_data() is the right method to use POST data, because I don't think this method gets called in POST requests (method only used in GET requests).

Have you tried other method of the CreateView?

I suggest you try the form_valid() method; here is another part of the docs with some examples https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-editing/#model-forms

  • Related