querateam / django-nextjs Goto Github PK
View Code? Open in Web Editor NEWNext.js integration for Django projects
License: MIT License
Next.js integration for Django projects
License: MIT License
Not gonna lie, im pretty new to NGINX, even after reading the documentation and the production tab for nginx I still don't understand how to configure it well to work seamlessly with this package. I have it working well in development, just the process of moving it to production with nginx's configuration is where im having issues. Any Help or examples would be greatly appreciated
Hi please how do you use django-nextjs with dynamice routes in nextjs like id/slug in urls
I have been using the django-nextjs library for my project and it has been a great help so far. However, I noticed that when I access the Next.js application directly on http://localhost:3000/ the JavaScript files are compressed with content-encoding gzip, but when I access the Django server (which is redirecting the files from Next.js), the files are no longer compressed.
I understand that the library does not currently support compression and I apologize if my request is an inconvenience. I have tried using the built-in GZipMiddleware in Django, but it did not work. I also tried using a reverse proxy like Nginx or Apache in front of my Django server, but it still doesn't work.
I would greatly appreciate it if compression support could be added to the django-nextjs library. This would make it easier for users like me to deliver compressed files to the client, improving performance and reducing bandwidth usage.
Thank you for your time and effort in maintaining this library, it has been a great help to me. Please let me know if you need any more information or if you have any questions.
how to passing data from django backend to next js pages?
i cant use {{ }} in next js pages
i am beginner in next js
Hi do you have a way to sync the 404 page in nextjs with the django backend error pages
views.py
from django_nextjs.render import render_nextjs_page_sync
def error_404(request, exception):
return render_nextjs_page_sync(request)
project/project/urls.py
handler404 = "apps.views.error_404"
Some type annotations are incorrect, e.g. the return type of render_nextjs_page_sync
and render_nextjs_page_async
.
django-nextjs/django_nextjs/render.py
Line 62 in d29b04e
django-nextjs/django_nextjs/render.py
Line 103 in d29b04e
django-nextjs/django_nextjs/render.py
Line 112 in d29b04e
django-nextjs/django_nextjs/render.py
Line 154 in d29b04e
While using django-nextjs, there is a situation where need to set allow_redirects to True, so I suggest adding the allow_redirects field as a parameter to functions such as render_nextjs_page_sync.
Please check here for details.
thank you.
Hello,
i've try to install the package like described in the readme.
Environment:
Everything was installed successfully but i have several errors:
First of all on index js i get the error: WebSocket connection to 'ws://127.0.0.1:8000/_next/webpack-hmr' failed:
But i can see the nextjs index.
Then i want to try to change the route to /test
I described a view and parsed it to the url.
If i call the url i got the error: too many redirects and the page wouldn't load:
Here my Settings.py:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-%2spqobsw&i$k(n(%(siwd#fxzh^h%wqk5nc3nx0_$upu8r5!q'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"django_nextjs",
]
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 = 'empire_next.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',
],
},
},
]
WSGI_APPLICATION = 'empire_next.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
views.py
from django.shortcuts import render
# Create your views here.
from django_nextjs.render import render_nextjs_page_sync
def index(request):
return render_nextjs_page_sync(request)
def test(request):
return render_nextjs_page_sync(request)
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("backend.urls")),
path("", include("django_nextjs.urls")),
]
backend.urly.py:
from django.urls import path
from .views import index
urlpatterns = [
path("", index, name="index"),
path("test/", index, name="test"),
]
any solution for this?
Can we use the Django==1.11.14 version with any code changes as its basic support version is Django==3.2?
It seems this package has a dependency with django 4.2. Any pointers how I can use it with Django=="3.1.4"?
I am occasionally getting this error in my logs coming from _render_nextjs_page_to_string:
CookieError at {path}
Attempt to set a reserved key 'expires'
For some reason, bing's crawler/bot has a cookie name set with the name expires
when it crawls my pages.
It seems that all cookies in the request are passed to _render_nextjs_page_to_string
which then further processes it in aiohttp.ClientSession
. Apparently it cannot handle cookies with reserved keywords. Perhaps we should sanitize the cookies by removing or ignoring the "expires" cookie name or any other cookie names with reserved keywords?
Full Traceback:
Traceback (most recent call last):
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib64/python3.8/concurrent/futures/_base.py", line 432, in result
return self.__get_result()
File "/usr/lib64/python3.8/concurrent/futures/_base.py", line 388, in __get_result
raise self._exception
File "/var/app/current/home/views.py", line 31, in nextjs_space_detail_slug
return await render_nextjs_page(request)
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django_nextjs/render.py", line 148, in render_nextjs_page
content, status, response_headers = await _render_nextjs_page_to_string(
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django_nextjs/render.py", line 99, in _render_nextjs_page_to_string
async with aiohttp.ClientSession(
File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/aiohttp/client.py", line 254, in __init__
self._cookie_jar.update_cookies(cookies)
File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/aiohttp/cookiejar.py", line 172, in update_cookies
tmp[name] = cookie # type: ignore[assignment]
File "/usr/lib64/python3.8/http/cookies.py", line 495, in __setitem__
self.__set(key, rval, cval)
File "/usr/lib64/python3.8/http/cookies.py", line 485, in __set
M.set(key, real_value, coded_value)
File "/usr/lib64/python3.8/http/cookies.py", line 350, in set
raise CookieError('Attempt to set a reserved key %r' % (key,))
Hello, I've encountered an issue when trying to integrate django-nextjs into my Django project. The issue arises when using ASGI and channels to run the server.
I have a URL path like so: url(r'^content', views.nextjs_content, name='content')
, and the associated view function is an asynchronous function:
async def nextjs_content(request):
return await render_nextjs_page(request)
Everything works perfectly fine in this setup, including Fast Refresh. However, when I introduce Server-Side Rendering (SSR) into my Next.js page (src/pages/content/[id].tsx), I start to encounter timeout errors. Specifically, my getServerSideProps function times out:
export async function getServerSideProps(context) {
const { id } = context.params
const url = `content/${id}/`
try {
const res = await axiosInstance.get(url)
return { props: { data: res?.data } }
} catch (error) {
return {
notFound: true,
}
}
}
The error I get is: AxiosError: timeout of 20000ms exceeded.
Interestingly, if I switch back to WSGI mode using python manage.py runserver --noasgi and add path("", include("django_nextjs.urls"))
to my URLs, everything works fine. However, in this setup, I lose the benefit of Fast Refresh.
Could you provide some guidance on this? It seems like there might be some issue with the interaction between ASGI, Django-Nextjs, and Next.js's SSR.
Thank you for your time!
hey my nextjs version is:
@next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ [email protected]
│ ├─ @next/[email protected]
│ ├─ resolve@^2.0.0-next.3
│ ├─ [email protected]
├─ [email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
│ ├─ @next/[email protected]
I am getting 'WebSocket connection to 'ws://localhost:8000/_next/webpack-hmr' failed: ' screenshot attached
After changing to Django channels and asgi.py in order to make websocket work, I tried all static files deployment configuration for Django 4, nothing works for correct loading vercel.svg. Please provide some guidance about this.
after changing to channels with asgi.py, 'admin' listed in urls.py can not accessed correctly. any guidance about how to handle middleware like this? Thanks,
my urls.py is:
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.generic.base import RedirectView
# from .views import jobs
# favicon_view = RedirectView.as_view(url='static/vercel.svg', permanent=True)
urlpatterns = [
# path('', jobs),
path('admin/', admin.site.urls),
re_path(r'^vercel\.svg$', RedirectView.as_view(url='static/vercel.svg')),
path('favicon.ico', RedirectView.as_view(url='static/favicon.ico')),
]
all these 3 paths are not working if channels and django-nextjs enabled in INSTALLED_APPS in settings.py.
I need to integrate with two next.js frontend.
one is for regular user and other is for admin.
The two frontends are separated, and one is on 3000 and other is on 3001
I need to use 3001 when I redirect to /admin
How can I solve this problem?
Does this support dynamic routing such as passing a slug?
I followed the steps from this tutorial. I added the created a new app called frontend and added the following codes:
# myproject/urls.py
from django.urls import include, path
urlpatterns = [
# ...
path("", include("frontend.urls")),
path("", include("django_nextjs.urls")),
]
# frontend/views.py
from django_nextjs.render import render_nextjs_page_sync
def index(request):
return render_nextjs_page_sync(request)
# frontend/urls.py
from django.urls import path
from .views import index
urlpatterns = [
path("", index, name="index"),
]
I can now see the homepage (situated at "localhost:8000/" route) But I can't visit any other routes like "http://localhost:8000/create" which I can visit from my nextjs server "http://localhost:3000/create".
I tried adding a new route in frontend.urls.py like this
from django.urls import path
from .views import index
urlpatterns = [
path("", index, name="index"),
path("create/", index, name="index"),
]
but I kept getting too many redirects. Can someone show me the correct way to do this or is it even necessary to add endpoints manually?
When using NextJS 13 with the new app router, client-side navigation is not working and <Link>
components cause the page to be reloaded, rather than replaced by JS. I've only tested this on the app router, so it's possible that the page router is also affected.
From what I can tell the issue is that requests made from the front-end use headers to tell the NextJS server if it should return full HTML or RSC. If the headers are not forwarded to NextJS, then the full HTML is always returned. NextJS also sets headers on the response that are required for this to work. These are the headers that I've found to be necessary:
Request/Response | Header Name |
---|---|
Request | Rsc |
Request | Next-Router-State-Tree |
Request | Next-Router-Prefetch |
Request | Next-Url |
Request | Cookie |
Request | Accept-Encoding |
Response | Vary |
Response | Content-Type |
I discovered the request headers by looking at the Vary
header for RSC requests.
I've got this working for me locally, so I'll open a PR with the changes I've made.
Hi when running django in product the css/js doesn't load or show
Hi,
If the Django server is set to run with debug=False
, then all the requests will pass through the render_nextjs_page_sync
, according to this statement in urls.py
:
if settings.DEBUG:
# only in dev environment
urlpatterns.append(re_path(r"^(?:_next|__nextjs|next).*$", NextJSProxyView.as_view()))
The problem is that all the .js
bundles requests will have their content-type
property set to text/html
, as this is happening for each request that passes through this view:
from django_nextjs.render import render_nextjs_page_sync
def index(request):
return render_nextjs_page_sync(request)
Should the content-type
be manually computed and then specified as an argument to the render_nextjs_page_sync
method? I don't see other way around it.
Thank you!
In Nextjs 13+, customize the root layout in app
directory:
// app/layout.jsx (or .tsx)
...
<body id="__django_nextjs_body" className={inter.className}>
<div id="__django_nextjs_body_begin" />
{children}
<div id="__django_nextjs_body_end" />
</body>
...
Write a django template that extends django_nextjs/document_base.html
:
{% extends "django_nextjs/document_base.html" %}
{% block head %}
<!-- ... the content you want to place at the beginning of "head" tag ... -->
{{ block.super }}
<!-- ... the content you want to place at the end of "head" tag ... -->
{% endblock %}
{% block body %}
... the content you want to place at the beginning of "body" tag ...
... e.g. include the navbar template ...
{{ block.super }}
... the content you want to place at the end of "body" tag ...
... e.g. include the footer template ...
{% endblock %}
Pass the template name to render_nextjs_page
:
async def jobs(request):
return await render_nextjs_page(request, "path/to/template.html")
is their any nextjs project with django like simple todo application
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.