Forums

Image Upload not working

I've created a form with an image upload in Django. It works on my local machine but something must be misconfigured on the server? When I submit the form it just reloads a blank form and nothing is entered into the database. My settings file:

MEDIA_ROOT  = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

My View

def add_book_view(request):

if request.method == 'POST':
    form = AddBookForm(request.POST, request.FILES)

    if form.is_valid():
        form.save()
        return redirect('books:book_list')
else:
    form = AddBookForm()
return render(request, 'settings/add_book.html', {'form' : form})

My form

<form method="POST" enctype="multipart/form-data">
      {% csrf_token %}
      <div class="form-font">
        Title:
      </div>
      <input class="settings-form-input" type="text" name="title" maxlength="256"
      required="" id="id_title">
      <div class="form-font">
        Author(s):
      </div>
      <input class="settings-form-input" type="text" name="authors" maxlength="256"
      required="" id="id_authors">
      <div class="form-font">
        Genre:
      </div>
      <div class="settings-form-input">
        <select name="genre" id="id_genre">
          <option value="0" selected="">None</option>
          <option value="1">Action-Adventure</option>
          <option value="2">Autobigraphy</option>
          <option value="3">Biography</option>
          <option value="4">Classic</option>
          <option value="5">Drama</option>
          <option value="6">Fantasy</option>
          <option value="7">Fiction</option>
          <option value="8">Historical</option>
          <option value="9">Mystery</option>
          <option value="10">Non-Fiction</option>
          <option value="11">Romance</option>
          <option value="12">Science-Fiction</option>
        </select>
      </div>
      <br/>
      <div class="form-font">
        Book Cover:
      </div>
      <input type="file" name="book_cover" accept="image/*" required="" id="id_book_cover">
      <br/><br/>
      <div class="form-font">
        Description:
      </div>
      <textarea class="settings-form-textarea" name="description" required=""
      id="id_description"></textarea>
      <input type="hidden" name="added_by" id="id_added_by" value="{{ user.first_name}}
      {{ user.last_name }}">
      <div class="form-button-container">
      <input type="submit" class="form-button" value="Add Book">
      </div>
    </form>

I have pillow in my virtual environment

I set my static and media urls on the WEB section. Any ideas what I'm doing wrong? Thanks.

My guess would be that your check if form.is_valid(): is returning False so your code is skipping that section of code. Check the validation code for your form. You can also add some debugging prints (prints to stderr will appear in your error log) to the validation code to see why it's failing.

That was it! In my forms.py I was including a date added field that I did not have in my template form, which was coming up as required. Problem solved, thank you!

Hi all I'm glad you were able to get this to work!

I'm having a similar issue but it seems to be path related as they system is unable to find the file I select to read data from it. It works find locally..

Ive tried many different ways to specify my path but no luck. GETTING:

No such file or directory: 'data-file.xlsx'

FORM:

<form class="" action="data" method="post">
  <input type="file" name="upload-file" value="">
  <input type="submit" name="" value="Submit">
</form>

App code:

from flask import Flask, render_template, request
import pandas as pd


app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

@app.route('/data', methods=['GET', 'POST'])
def data():
    if request.method == 'POST':
        file = request.form['upload-file']
        data = pd.read_excel(file)
        return render_template('data.html', data=data.to_html()) #to_dict() #to_html()


if __name__ == '__main__':
    app.run(debug=True)

<br><br> ERROR LOG:<br>

 2022-06-24 19:08:41,750: Exception on /data [POST]
    Traceback (most recent call last):
      File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2051, in wsgi_app
        response = self.full_dispatch_request()
      File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1501, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1499, in full_dispatch_request
        rv = self.dispatch_request()
      File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1485, in dispatch_request
        return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
      File "/home/CSVchecker/flask_app.py", line 33, in data
        data = pd.read_excel(file)
      File "/usr/local/lib/python3.9/site-packages/pandas/util/_decorators.py", line 296, in wrapper
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 304, in read_excel
        io = ExcelFile(io, engine=engine)
      File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 867, in __init__
        self._reader = self._engines[engine](self._io)
      File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_xlrd.py", line 22, in __init__
        super().__init__(filepath_or_buffer)
      File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 353, in __init__
        self.book = self.load_workbook(filepath_or_buffer)
      File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_xlrd.py", line 37, in load_workbook
        return open_workbook(filepath_or_buffer)
      File "/usr/local/lib/python3.9/site-packages/xlrd/__init__.py", line 166, in open_workbook
        file_format = inspect_format(filename, file_contents)
      File "/usr/local/lib/python3.9/site-packages/xlrd/__init__.py", line 60, in inspect_format
        with open(path, "rb") as f:
    FileNotFoundError: [Errno 2] No such file or directory: 'data-file.xlsx'

Make sure that the file is being saved and can be found at the given path.