QueraTeam / django-nextjs

Next.js integration for Django projects
MIT License
341 stars 17 forks source link

Issue when running nextjs #4

Closed aashishg closed 2 years ago

aashishg commented 2 years ago

hey my nextjs version is:

@next/env@12.1.6
├─ @next/eslint-plugin-next@12.1.6
├─ @next/swc-android-arm-eabi@12.1.6
├─ @next/swc-android-arm64@12.1.6
├─ @next/swc-darwin-arm64@12.1.6
├─ @next/swc-darwin-x64@12.1.6
├─ @next/swc-linux-arm-gnueabihf@12.1.6
├─ @next/swc-linux-arm64-gnu@12.1.6
├─ @next/swc-linux-arm64-musl@12.1.6
├─ @next/swc-linux-x64-gnu@12.1.6
├─ @next/swc-linux-x64-musl@12.1.6
├─ @next/swc-win32-arm64-msvc@12.1.6
├─ @next/swc-win32-ia32-msvc@12.1.6
├─ @next/swc-win32-x64-msvc@12.1.6
├─ eslint-config-next@12.1.6
│  ├─ @next/eslint-plugin-next@12.1.6
│  ├─ resolve@^2.0.0-next.3
│  ├─ resolve@2.0.0-next.3
├─ next@12.1.6
│  ├─ @next/env@12.1.6
│  ├─ @next/swc-android-arm-eabi@12.1.6
│  ├─ @next/swc-android-arm64@12.1.6
│  ├─ @next/swc-darwin-arm64@12.1.6
│  ├─ @next/swc-darwin-x64@12.1.6
│  ├─ @next/swc-linux-arm-gnueabihf@12.1.6
│  ├─ @next/swc-linux-arm64-gnu@12.1.6
│  ├─ @next/swc-linux-arm64-musl@12.1.6
│  ├─ @next/swc-linux-x64-gnu@12.1.6
│  ├─ @next/swc-linux-x64-musl@12.1.6
│  ├─ @next/swc-win32-arm64-msvc@12.1.6
│  ├─ @next/swc-win32-ia32-msvc@12.1.6
│  ├─ @next/swc-win32-x64-msvc@12.1.6

I am getting 'WebSocket connection to 'ws://localhost:8000/_next/webpack-hmr' failed: ' screenshot attached

Screenshot at May 26 22-07-27
danialkeimasi commented 2 years ago

Hi,

to be able to get Webpack-HMR (hot module replacement) in nextjs 12 and above, you should setup django-channels and add NextJSProxyHttpConsumer and NextJSProxyWebsocketConsumer consumers in to your asgi.py (mentioned on README.md).

aashishg commented 2 years ago

it gives

raise ValueError("No route found for path %r." % path)
ValueError: No route found for path ''.

apps/app1/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.jobs, name='index'),
]

urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
   #if i set both or one or none it still gives same error written above
    path('', include('apps.app1.urls')),
    # path('', include("django_nextjs.urls")),

    path('admin/', admin.site.urls),
]

settings.py

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'apps.app1.apps.App1Config',
    'django_nextjs',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
ASGI_APPLICATION = "asgi.application"
WSGI_APPLICATION = 'wsgi.application'

apps/app1/apps.py

from django.apps import AppConfig

class App1Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.app1'

asgi.py

import os

from django.core.asgi import get_asgi_application
from django.urls import path, re_path

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django_nextjs.proxy import NextJSProxyHttpConsumer, NextJSProxyWebsocketConsumer
from django.conf import settings

http_routes = []
websocket_routers = []
if settings.DEBUG:
    http_routes.insert(0, re_path(r"^(?:_next|__next|next).*", NextJSProxyHttpConsumer.as_asgi()))
    websocket_routers.insert(0, path("_next/webpack-hmr", NextJSProxyWebsocketConsumer.as_asgi()))

application = ProtocolTypeRouter(
    {
        # Django's ASGI application to handle traditional HTTP and websocket requests.
        "http": URLRouter(http_routes),
        "websocket": AuthMiddlewareStack(URLRouter(websocket_routers)),
        # ...
    }
)

views.py

# Create your views here.

# If you're using django channels
from django.http import HttpResponse
from django_nextjs.render import render_nextjs_page_async

async def jobs(request):
    return await render_nextjs_page_async(request)

as in the given django doc url in the django-nextjs readme it has written to add middleware or make it async-capable since i cant find how to make the existing middleware async capable i added my own by using example in doc:

import asyncio
from django.utils.decorators import sync_and_async_middleware

@sync_and_async_middleware
def simple_middleware(get_response):
    # One-time configuration and initialization goes here.
    if asyncio.iscoroutinefunction(get_response):
        async def middleware(request):
            # Do something here!
            response = await get_response(request)
            return response

    else:
        def middleware(request):
            # Do something here!
            response = get_response(request)
            return response

    return middleware

then I added it in the settings.py MIDDLEWARE array as 'middleware.simple_middleware'

but it gave

raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'asgi'

my nextjs is running at 3000 & django at 8000

danialkeimasi commented 2 years ago

I think the last lines in your settings.py is not correct. The following settings indicate that you moved your asgi.py and wsgi.py files to the root directory (next to manage.py).

ASGI_APPLICATION = "asgi.application"
WSGI_APPLICATION = 'wsgi.application'

Did you move your asgi and wsgi files to root directory?

aashishg commented 2 years ago

yes all project files i moved, here is my project structure:

backend(django) >
  __init__.py (empty)
  asgi.py
  manage.py
  wsgi.py
  middleware.py (not using) (copy pasted contents above)
  urls.py
  settings.py
  apps/app1 >
    migrations
    __init__.py
    apps.py
    models.py
    tests.py
    urls.py
    views.py
frontend(nextjs) (default yarn create next-app -ts  folder structure with no modification)

note: localhost:3000 works fine technically middleware & asgi are on same file tree branch so idk why it cant get it

danialkeimasi commented 2 years ago

I've created an empty project with your codes. In the asgi.py file change the http_routes = [] to http_routes = [re_path(r"", asgi_application)]. It'll be fixed.

aashishg commented 2 years ago

works, thanks