Search code examples
pythondjangotext-processing

DJango: Textarea/Form get, process and show


Good evening, i'm currently working on a small DJango project, and am currently facing an issue: The whole of the project is to provide a textarea to the user:

1- let the user write down the text that will be worked with.

2- store the data to process/work on it using python.

3- store the processed data on another variable.

4- show the text on a second textarea provided on screen.

Currently, I've tried using a simple to get the information and store it, but the site keeps spinning and there's no progress

Base .html section with the textareas:

    <section id="det">
        <div class="theText">
            <textarea id="text" placeholder="Type/Paste to Summarize"></textarea>
            <br>
            <button type="submit">Start</button>
            <br><br>
            <button type="submit">Clean</button>
            <br><br>
        </div>
    
        <div class="theText">
            <textarea id="text" placeholder="Your summarized text"></textarea>
            <br>
            <button type="submit">Export</button>
            <br><br>
            <button type="submit">Copy</button>
            <br><br>
        </div>
    </section>

Alternative tried:

<form method="POST">
            {% csrf_token %}
            <label for='TPre'>PreSummarizarion</label><br>
            <input id="TPre" name="TPre" type="text"><br>
            <button>Submit</button>
</form>

Current views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return render(request, "first/home.html",{
        "text":text,
    })

def taking(request,tex,tex_slug):
    tex= textPre.objects.get(slug = tex_slug)
    return render(request, "first/home.html", {
        "tex":tex
    })

Current models on the django project:

from django.db import models

class textPre(models.Model):
    preText = models.TextField()
    #preText2 = models.CharField(max_length=1500)
    
class textPost(models.Model):
    posText = models.TextField()
    #posText2 = models.CharField(max_length=1500)
    
def __str__(self):
    return f"{self.preText}"

#def save(self, *args, **kwargs):
#    super().save(*args, **kwargs)
#    self.slug = self.id
#    super().save(*args, **kwargs)

Whereas; preText would be user to store the data, and posText will contain the new text that was processed using python.

Questions: 1- How can I store the user input from the textareas on to a variable to work on it using python? 2- How can I show the processed information on the second textareas space?

(Note: Relatively new to DJango here, have tried a couple other methods and course materials, but to no avail)


Solution

  • From scratch. You do not need two Models, just one with two fields is fine. To make a process over one of the two fields you can override .save method of the model:

    models.py

    def process_text_field(text):
        processed_text = text.lower()
        processed_text = 'Processed Text:\n' + processed_text
        return processed_text
    
    class TextProcess(models.Model):
        original = models.TextField()
        processed = models.TextField()
    
        def save(self, *args, **kwargs):
            self.processed = process_text_field(self.original)
            return super().save(*args, **kwargs)
    

    For example, by writing a function that would process the original field and assign the result to processed.

    views.py

    def index(request):
        obj_instance = None
    
        if request.method == 'POST':
            original = request.POST.get('text')
            obj_instance = TextProcess.objects.create(original=original)
    
        return render(request, "index.html",{'text': obj_instance})
    

    index.html

    {% block content %}
    <section id="det">
        <form action="{% url 'index' %}" method="post">
            {% csrf_token %}
            <div class="theText">
                <textarea name="text" placeholder="Type/Paste to Summarize"></textarea>
                <br>
                <button type="submit">Start</button>
                <button >Clean</button>
                <br><br>
            </div>
        </form>
    
        {% if text %}
        <div class="theText">
            <textarea placeholder="Your summarized text">{{text.processed}}</textarea>
        </div>
        {% endif %}
    </section>
    {% endblock %}
    

    The same template is rendered, for both entering and displaying information. The difference is that on GET requests there is no object instance created (handled at the view), so only the first block (to enter the text) will be displayed (because of the if condition).

    If you are wondering about the URL, that is just a way to obtain the full path by using the reverse resolution:

    urls.py

    urlpatterns = [
        path('', index, name='index'),
    ]
    

    I must say that there are other approaches, you could do the processing in other places for example in the view. But in programming you always want to separate your logic as much as possible, following the single responsibility principle.