Vlad Shlyanin
Vlad Shlyanin

Reputation: 57

Django "TemplateView" and "/media/" url conflict

I am writing an SPA with Django 1.11 (switching to 2.0 is no an option), as backend, getting all the data from Django Rest Framework API and I route my app via React routing.

Here is my my main urls.py :

urlpatterns = [
    url(r'^api/', include('text_cms.urls')),
    url(r'^api/', include('photos_admin.urls')),
    url(r'^admin/', admin.site.urls),
    url('', TemplateView.as_view(template_name='index.html'),
    ]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And here is my settings.py file:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media-files/'

The issue is, that the particular url setting

url('', TemplateView.as_view(template_name='index.html'),

is messing up media url, and files uploaded by user cannot be reached by url link, even though they are saved to folder, I just get a 404 error. When I comment my "Template as view" url, delete it or just give it another address, like url('main/') - everything works fine again.

I've tried to serve the template from the other app and registering it in the main urls.py file, but it did not work too

urlpatterns = [
    url(r'^', views.IndexView),
]

views.py

def IndexView(request):
    return render(request, 'main/index.html', {})

Upvotes: 0

Views: 591

Answers (1)

Carl Brubaker
Carl Brubaker

Reputation: 1655

url('', TemplateView.as_view(template_name='index.html'),

You are missing a closing ). It also appears that you url pattern is incorrect as well. Should be

url(r'^$' , TemplateView.as_view(template_name='index.html')),

Upvotes: 1

Related Questions