skip to Main Content

I have a Django backend in which I have pasted build directory of react project (after running npm run build). I see a bunch of web pages of react project opening when opened through code, i.e. <Link className='dropdown-item' to='/customer/dashboard'>Dashboard</Link> opens the component routed by <Route path="/customer/dashboard" element={<Dashboard />} /> (i.e. Dashboard component launches). But if I update the URL to http://127.0.0.1:8000/customer/dashboard or even refresh the page with the aforementioned URL, I get 404 error.
I also have another problem where some of the pages don’t even open through code. So I am wondering why this could be.

Following is the code snippets I have in urls.py (Django project)

path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
path('', views.index, name = 'index'),

views.py

from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache

index = never_cache(TemplateView.as_view(template_name='index.html'))

2

Answers


  1. You ought to prevent client side routes from reaching the server. Use <HashRouter> [react router docs] to envelope all your routes.

    Login or Signup to reply.
  2. From my understanding I would suggest the following way is standard way to handle Django url.py

    
    from django.contrib import admin
    from django.urls import path,include,re_path
    from django.conf import settings
    from django.conf.urls.static import static
    
    
    from django.views.generic import TemplateView
    
    from django.conf  import settings
    urlpatterns = [
        # Sample routes:
        path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),#yours
        path('admin/', admin.site.urls), # Admin Route
        path('api/', include('api.urls')), # Other Project route
    
    ]
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Handle static and media files 
    urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] # Handle all other routes with React.. I mean all routes that are not defined above
    
    

    The above code snippet will be dynamic for most use case.

    Incase React I would suggest Browser Router. And this both combo works well in production too.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search