Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin returns 404 on POST, 200 on GET

Tags:

python

django

On production server, when I try to edit/create an object then saving fails, returning 404. This only occurs for POST requests, GET requests (loading the page) work fine. Django is deployed via cPanel and WSGI, DEBUG is False (though it does not work even when it's set to True)

I have deployed the Django app with cpanel, running in a virtualenv. This only seems to happen for a model that uses FileField for file upload, other models can be changed/created just fine.

The model:

def get_image_path(instance, filename):
    name, ext = filename.split('.')
    return f'images/{instance.advert_id}/{name}.{ext}'

class AdvertImage(models.Model):
    advert = models.ForeignKey(Advert, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=get_image_path)

URL conf:

urlpatterns = [
                  path('i18n/', include('django.conf.urls.i18n')),
              ] + i18n_patterns(
    path('admin/', admin_site.urls),

    # ... other views....

    prefix_default_language=False
)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Navigate to domain.com/admin/colli/advertimage/1/change/ - the page loads correctly. Fill the form, click save.

The model should be saved and no 404 should occur.
Other models, that do not use FileField, for them all admin views work correctly

With DEBUG=True, the full error message is:

Page not found (404)
Request Method: POST
Request URL:    http://example.com/admin/colli/advertimage/1/change/
Raised by:  django.contrib.admin.options.change_view
Using the URLconf defined in Colli.urls, Django tried these URL patterns, in this order:

i18n/
admin/
[name='home']
advert/<slug:slug> [name='detail']
tagauks [name='admin_list']
tagauks/lisa [name='insert']
tagauks/muuda/<int:pk> [name='edit']
tagauks/kasutaja/<int:pk> [name='user_edit']
tagauks/save_image [name='save_image']
accounts/login/ [name='login']
accounts/logout/ [name='logout']
api/
^media/(?P<path>.*)$
The current path, colli/advertimage/1/change/, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

The view causing this seems to be change_view

like image 680
taurijuhkam Avatar asked Aug 04 '19 07:08

taurijuhkam


1 Answers

Have you activated middleware (Internationalization: in URL patterns)?

# settings.py
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
...
]
like image 55
Alejandroid Avatar answered Oct 20 '22 22:10

Alejandroid