Django with NextJS integration



如何有效地将Django与NextJS集成?你能分享一下吗?如果你有任何公共项目!或者完成它的方法!

我没有使用NextJS的经验,但我认为你正在搜索的是CORS。Django-Cors-Headers包将完成这项工作,并提供了关于如何设置的完美文档。然后,您的NextJS应用程序可以使用类似Axios的东西从Django Back-end API获取适当的数据。

编码快乐!

我用现代React构建了一个管理控制台,但有Django的支持。

  • 输入:Django(Admin(+Next.js
  • 输出:
    • Next.js用于管理页面
    • Django用于后端、登录到仪表板、用户管理。Admins页面是通过Django模板嵌入Next.js页面实现的
    • API也可以用Django views实现

步骤:

  • 不使用getServerSideProps实现Next.js页面,如果需要,请使用useEffect从后端获取数据
  • 创建简单的Django模板和视图,只需使用% include %(Django Template Syntax(嵌入Next.js页面
  • 可以在next.config.js中设置assetPrefix,以防止next.js和Django之间的静态文件冲突

试图展示天真的例子:

// Next.js project
// /pages/post/index.js
...
useEffect(() => {
fetchPosts(...).then(data 
});
// /pages/post/[id].js
...
const router = useRouter();
const { id } = router.query;
useEffect(() => {
fetchPost(id).then()...
});
// npm run export
out/_next
out/post.html
out/post/[id].html
// use gulp.js or sth to copy the exported files (`out`) into Django project (`static` and `templates` folder)
django-app/static/_next // I copy _next into static and make Django serve its statics + Next.js _next
// These two pages above from out
django-app/templates/next-admin/post.html  
django-app/templates/next-admin/post/[id].html
// Django project
// templates
// django-app/templates/post/list.html
{% block content %}
{% include "next-admin/post.html" %}
{% endblock %}
// django-app/templates/post/detail.html
{% block content %}
{% include "next-admin/post/[id].html" %}
{% endblock %}
// views.py
def post_list_view(request):
return render(request, 'post/list.html', {})
def post_detail_view(request, _id):
return render(request, 'post/detail.html', {"id": _id})
// urls.py
path('post', post_list_ivew, name='post-list'),
path('post/<str:_id>', post_detail_view, name='post-detail'),
// Next.js npm run export -> Django python manage.py runserver
// Maybe you have to install corsheader for client data fetching
// And custom the admin/base.html or base_site.html for adding navigation links to your admin pages built by Next.js

结论:

  • Django(admin(有一个强大的用户管理系统(角色、组…(,我喜欢它
  • 但我想为管理界面带来一种新的React,我们可以通过Next.js实现,也可以创建React应用程序
  • 希望我的想法能帮到你。我试着尽可能简单地写下我在现实世界中的例子

最新更新