Forums

Handling requests for index.html with a hybrid Django-React app that has Django in charge of serving HTML pages

Background

I am trying to deploy an app with Django backend and React frontend (the latter is a Create-React-App). This is my first web app so I have never tried to deploy anything before.

To get these to work together I have followed the approach in https://fractalideas.com/blog/making-react-and-django-play-well-together-hybrid-app-model/.

In development, this relied on Django and React running on two servers, with Django in charge of serving HTML pages. To quote from the article: a view rendered the index.html generated by Create-React-App with the Django template engine. A catchall URL routes any unrecognised URL with that view. The frontend URL router takes over and renders the appropriate page on the client side. This worked fine in development. Given my lack of experience in these matters, I merely copied the code for the catchall view that proxies requests for index.html to the React development server.

Now I am not sure what too do about it in deployment, as I cannot get it to work as anticipated . This is where I have got to (I have amended the view a little):

The url in urls.py:

re_path(r'', views.catchall),

The view in views.py:

@csrf_exempt
def catchall(request, upstream='http://SouthernSeashores.pythonanywhere.com:3000'):
#def catchall_dev(request, upstream='http://localhost:3000'):

    """
    Proxy HTTP requests to the frontend dev server in development.

    The implementation is very basic e.g. it doesn't handle HTTP headers.

    """
    upstream_url = upstream + request.path
    method = request.META['REQUEST_METHOD'].lower()
    response = getattr(requests, method)(upstream_url, stream=True)
    content_type = response.headers.get('Content-Type')

    if request.META.get('HTTP_UPGRADE', '').lower() == 'websocket':
        return http.HttpResponse(
            content="WebSocket connections aren't supported",
            status=501,
            reason="Not Implemented"
        )

    elif content_type == 'text/html; charset=UTF-8':
        return http.HttpResponse(
            content=engines['django'].from_string(response.text).render(),
            status=response.status_code,
            reason=response.reason,
        )

    else:
        return http.StreamingHttpResponse(
            streaming_content=response.iter_content(2 ** 12),
            content_type=content_type,
            status=response.status_code,
            reason=response.reason,
        )

# amended for production
catchall = TemplateView.as_view(template_name='index.html')

#catchall = catchall_dev if settings.DEBUG else catchall_prod

The error message I am getting appears to be from views.py:

Exception Type: NameError Exception Value:
name '_______' is not defined

Given my lack of experience, I don't really understand how to get the React frontend and Django backend to communicate in deployment.Has anyone any experience with deploying a Django-React 'hybrid app' coded in this way able to advise me please?

Could you share full traceback?

Here's the traceback

2021-07-11 11:30:11,809: Internal Server Error: / Traceback (most recent call last): File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 556, in resolve for pattern in self.url_patterns: File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in get__ res = instance.dict[self.name] = self.func(instance) File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.9/importlib/init.py", line 127, in import_module return bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/SouthernSeashores/backend/mapobs/urls.py", line 22, in <module> from mapobs.views import UserAPIView, UsernameView File "/home/SouthernSeashores/backend/mapobs/views.py", line 178, in <module> __________ NameError: name '_______' is not defined

I've formatted the traceback:

2021-07-11 11:30:11,809: Internal Server Error: /
 Traceback (most recent call last):
    File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 167, in _get_response
callback, callback_args, callback_kwargs = self.resolve_request(request)

File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 290, in resolve_request
resolver_match = resolver.resolve(request.path_info)
File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 556, in resolve
for pattern in self.url_patterns:
File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/SouthernSeashores/.virtualenvs/coastal_obs-virtualenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/SouthernSeashores/backend/mapobs/urls.py", line 22, in <module>
from mapobs.views import UserAPIView, UsernameView
File "/home/SouthernSeashores/backend/mapobs/views.py", line 178, in <module>
_____________________________________
NameError: name '_____________________________________' is not defined

How does line 178 in /home/SouthernSeashores/backend/mapobs/views.py look like?

UPDATE: The name error turned out to be a red herring - I had lost the '#' in front of a line at the end of the catchall in views.py (oops). I am now trying to circumvent the catchall by using this re-path line in urls.py :

re_path('(^(?!(api|admin)).*$)', TemplateView.as_view(template_name="index.html")),

That seems to have eliminated the error message. But I can't tell properly until I do some dead code elimination to properly configure my React frontend (according to the console message). I'll give that ago.

That worked.

Glad you figured that out!