How to view my index.html template in the Django restframework?

Asked

Viewed 309 times

0

I have a problem with a test I have to deliver for a selection process I’m conducting. I’ve tried every possible and imaginable way to solve it, but I couldn’t. When trying to call an index.html file that is inside a templates/api folder so that it becomes the root of the url (http://127.0.0.1:8000) Django doesn’t recognize her. Follows codes:

File urls.py of my folder sisquestoes(root, folder that contains setings.py): PS: I already changed the name of this api and still does not locate the template .

urlpatterns = [
    path(r'admin/', admin.site.urls),
    path('', include('api.urls')),
    url(r'^', include('api.urls','app_name')),
]

Api folder urls.py file (which has the admin.py folder and the files and templates/api/index.html):

router = routers.DefaultRouter()
router.register('questoes', views.QuestoesView)
router.register('user', views.UserView)

app_name="api"
urlpatterns = [
path('', include(router.urls)),
url(r'^$', views.index, name='index'),
]

Function in views.py:

from django.shortcuts import render
from . import views

  def index(request):
      return render(request,'api/index.html')

I honestly spent the whole night trying to solve read virtually all documentation, I went through various paths and tutorials and nothing. I am waiting for some solidarity and dear soul. Great hug.

  • If you use the Rest framework, why render an index? Does that make sense? Ideally you should serve a restful api. Rendering html should not be the responsibility of the Rest framework, this is my opinion. If I could explain better the use case.

1 answer

0

The default to include urls in Django has changed in version 2.0 No longer used the url, and yes the path.

With this change, regex is no longer used to define a url (at least not with path).

Therefore:

# Raiz
urlpatterns = [
    path(r'admin/', admin.site.urls),
    path('', include('api.urls')),
    # url(r'^', include('api.urls','app_name')),
]


#views.py
router = routers.DefaultRouter()
router.register('questoes', views.QuestoesView)
router.register('user', views.UserView)

app_name="api"
urlpatterns = [
    path('', views.index, name='index'),
    path('', include(router.urls)),
    # url(r'^$', views.index, name='index'),
]

Remembering that the structure of the folder where the index.html is located should be root/api/templates/api/index.html.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.