How to read text file and show content in textarea with Django python?

Question:

I have a Django application. And I can upload files. But now I want to show the text from a text file in a text area.

So I have this:

forms.py:


class ProfileForm(forms.Form):
    upload_file = forms.FileField()

models.py:

class UploadFile(models.Model):
    image = models.FileField(upload_to="images")

vieuws.py:

class CreateProfileView(View):
    def get(self, request):
        form = ProfileForm()
        return render(request, "main/create_profile.html", {
            "form": form
        })

    def post(self, request):
        submitted_form = ProfileForm(request.POST, request.FILES)

        if submitted_form.is_valid():
            uploadfile = UploadFile(image=request.FILES["upload_file"])
            uploadfile.save()
            return HttpResponseRedirect("/")

        return render(request, "main/create_profile.html", {
            "form": submitted_form
        })

and the html file:

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Create a Profile</title>
    <link rel="stylesheet" href="{% static "main/styles/styles.css" %}">
  </head>
  <body>
    <form action="/" method="post" enctype="multipart/form-data">
      {% csrf_token %} {{ form }}
      <button type="submit">Upload!</button>
    </form>   

    <textarea name="" id="" cols="30" rows="10"></textarea>
  </body>
</html>

And I have this textfile: yes.txt with this content: Yes, we can.

So my question is how to output this text in the textarea?

Asked By: mightycode Newton

||

Answers:

You could get the text of the uploaded file in the view and add it as a message (don’t forget to import messages from django.contrib in the views.py file) and afterwards display it inside the textarea. My code looks like the following and works.

views.py

    def post(self, request):
        submitted_form = ProfileForm(request.POST, request.FILES)
        if submitted_form.is_valid():
            uploadfile = UploadFile(my_file=request.FILES["upload_file"])
            uploadfile.save()
            # Get the text of the file of the instance
            with open(uploadfile.my_file.path) as f:
                lines = f.readlines()
            # Add the text as message
            messages.add_message(request, message=lines, level=messages.INFO)
            return HttpResponseRedirect("/")
        return render(request, "create_profile.html", {
        "form": submitted_form
        })

template.html*

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Create a Profile</title>
    <link rel="stylesheet" href="{% static "main/styles/styles.css" %}">
</head>
<body>
<form action="/" method="post" enctype="multipart/form-data">
    {% csrf_token %} {{ form }}
    <button type="submit">Upload!</button>
</form>
{% for message in messages %}
    {% if message %}
        <textarea name="" id="" cols="30" rows="10" >{{ message }}</textarea>
    {% endif %}
{% endfor %}
Answered By: reez.zeer

Without using messages which appear only one-time as notifications, use in following way instead.

views.py:

from django.conf import settings
import os


class CreateProfileView(View):
    def get(self, request):
        form = ProfileForm()
        return render(request, "main/create_profile.html", {
            "form": form
        })

    def post(self, request):
        submitted_form = ProfileForm(request.POST, request.FILES)
        content = ''

        if submitted_form.is_valid():
            uploadfile = UploadFile(image=request.FILES["upload_file"])
            uploadfile.save()
            with open(os.path.join(settings.MEDIA_ROOT,
                                   f"{uploadfile.image}"), 'r') as f:
                content = f.read()

            print(content)
            return render(request, "main/create_profile.html", {
                'form': ProfileForm(),
                "content": content
            })

        return render(request, "main/create_profile.html", {
            "form": submitted_form,
        })

main/create_profile.html:

<form action="/" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
     {{ form }}
    <button type="submit">Upload!</button>
</form>   
{% if content %}
    <textarea name="" id="" cols="30" rows="10">{{content}}</textarea>
{% endif %}
Answered By: Sunderam Dubey