1

I have a simple model and I want to save it using the ModelForm.

Here's the code:

#models.py
class MyArchive(models.Model):
    archive_id = models.CharField(max_length = 20, primary_key=True)
    description = models.CharField(max_length = 50, blank = True)
    archive_file = models.FileField(upload_to = "my_archives/")

#views.py
class MyArchiveForm(ModelForm):
    class Meta:
        model = MyArchive
def upload(request):
    if request.method == 'POST':
        form = MyArchiveForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('uploaded success!')
        else:
            logger.debug("invalid form")
    return HttpResponse('upload fail!')

I've synced DB and saw the tables created. But every time it goes to form.save then says

DatabaseError, no such table. 

Is my way to save using ModelForm wrong?

UPDATE: What's even weird that when I removed this line: form.save(), it fails at if form.is_valid() with the same error no such table, but when I run django in debug mode, if form.is_valid() works fine.

ThemeZ
  • 473
  • 1
  • 5
  • 15

1 Answers1

0

It's a little trick, turns out led by bad database configuration, I was using relative path in settings.py, so it didn't find the db file at running time, but when run django sycdb, it can find where the db loc.

'default' : {
    'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
    'NAME': 'sqlite.db',                      # Or path to database file if using sqlite3.
}

UPDATE: To use relative path on db file, I should have db setting like this:

from os.path import dirname, join

PROJECT_DIR = dirname(__file__)

DATABASES = {
    # ...
    'NAME': join(PROJECT_DIR, 'sqlite.db'),
    # ...
}

see Can I make the Django database path (for sqlite3) "cross-platform"?

Community
  • 1
  • 1
ThemeZ
  • 473
  • 1
  • 5
  • 15