Forums

Is it possible to upload images with django without using a database on pythonanywhere?

Hi,

I'm working on a small website project at pythonanywhere.com.Website I'm working on has ASCII image converter in it. The website has no errors when I run it on my local server. 

It also works well at pythonanywhere, but when I upload an image to convert it to ASCII image and submit, instead of keep running and converting the image to ASCII image, I keep getting "no such table" error. Once again, I had no such error when I ran this website on local server. 

I didn't use database for my website and I would like to avoid using it as long as possible. My question is, is there a way for me to run my website without creating/using database on pythonanywhere.com? or do I have to create one? 

P.S.: I use Python 3.8.5 and Django 3.1.1

You can find my views.py and models.py files below.  

My views.py file is as following:

from django.shortcuts import render, HttpResponse
from django.http import HttpResponse
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import FilesUpload
from .asciicode import main, give_result
import os


def home(request):
    if request.method == "POST":
        file2 = request.FILES["file"]
        document = FilesUpload.objects.create(file=file2)
        document.save()
        main()
        result_path = give_result()
        print(result_path)
        return render(request, "result.html", result_path)
        #return HttpResponse("Your file was uploaded")
    return render(request, "upload.html")

And this is my models.py file:

from django.db import models

# Create your models here.
class FilesUpload(models.Model):
    file = models.FileField(upload_to='/home/seoapp/asciiconverter/media/images/')

[edited by admin: code formatting]

If you don't want to use database you can't use models. Maybe form FileFIeld is what need?

Thank you for the answer, I figured out how to use database (I forgot to make migrations) so I dont get the error anymore. But there is a new problem!! It should be possible to download the uploaded image (which was converted to ASCII image), But it gives back an empty html file instead of txt file. Since there is no error message, what can I do??

What code have you written in your view to handle the download?

You can see view file above; and please see below for reference to codes related to download;

<html>
<link rel="stylesheet" href="/static/css/style.css">
<body>
<section class="container">
    <div class="left-half">
        <div class="header">
            <img src="media/logo.png" width="200px" alt="logo" />
        </div>
        <div class="middle">
            <p><a class="link" href="{{ new_path }}" download>Here is your result!</a></p>
        </div>
        <div class="footer">
            <p>Footer</p>
        </div>
    </div>
    <div class="right-half">
        <a class="link" href="/" target="_parent">You can click here to upload new image</a>
    </div>
</section>
</body>

</html>

AND

import PIL.Image
import glob
import os, shutil

ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", "," , "."]

def resize_image (image, new_width=100):
    width, height = image.size
    ratio = height / width
    new_height = int(new_width * ratio)
    resized_image = image.resize((new_width, new_height))
    return(resized_image)

def grayify(image):
    grayscale_image = image.convert("L")
    return (grayscale_image)

def pixels_to_ascii(image):
    pixels = image.getdata()
    characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
    return (characters)


def main(new_width=100):



#path = input("Enter a valid pathname to an image:\n")
    global completeName
    list_of_files = glob.glob('/home/seoapp/asciiconverter/media/images/*')
    path = max(list_of_files, key=os.path.getctime)
    print("test" + path)
    try:
        image = PIL.Image.open(path)
    except:
        print(path, " is not a valid pathname to an image.")


    new_image_data = pixels_to_ascii(grayify(resize_image(image)))

    pixel_count = len(new_image_data)
    ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))

    print (ascii_image)

    image_name = path[60:]
    print(image_name)

#how to define path for result text files:
    save_path = '/home/seoapp/asciiconverter/media/results/'

    completeName = os.path.join(save_path, image_name + ".txt")

    print(completeName)


    #ascii_image_file = image_name + ".txt"
#    os.makedirs(os.path.dirname(ascii_image_file), exist_ok=True)
with open(completeName, "w") as f:
    f.write(ascii_image)

def give_result():
    media_result = completeName[47:]
    complete_name_result = {"new_path": media_result}
    return complete_name_result


if not os.listdir('/home/seoapp/asciiconverter/media/images/'):
    pass
else:
    main()

** edit by admin to fix formatting **

I tried to indent your code to get the formatting to make it legible, but I can't know if I got it right. Have you checked the contents of the file on the disk? Perhaps there's something in your code that is just writing an empty file. Also, you may not be serving the file from the correct URL. Have a look at https://help.pythonanywhere.com/pages/DebuggingStaticFiles/ to ensure that you are serving and accessing the files correctly.

Hi,

Does html2image libray support in pythonanywhere because i try to screenshot the html file and save it in a specified folder i dont get the image saved.

[edit] I see that you posted about this on a new forum thread, so I've answered there.