Coder Social home page Coder Social logo

Comments (6)

danialkeimasi avatar danialkeimasi commented on August 31, 2024

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).

from django-nextjs.

aashishg avatar aashishg commented on August 31, 2024

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

from django-nextjs.

danialkeimasi avatar danialkeimasi commented on August 31, 2024

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?

from django-nextjs.

aashishg avatar aashishg commented on August 31, 2024

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

from django-nextjs.

danialkeimasi avatar danialkeimasi commented on August 31, 2024

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.

from django-nextjs.

aashishg avatar aashishg commented on August 31, 2024

works, thanks

from django-nextjs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.