我正在使用Django休息框架处理Angular5。
我正在尝试将Django url与angular5集成。它只适用于索引页面。如果我们通过点击任何按钮改变状态它的工作正常,但在页面加载时显示“找不到页面(404)”。
索引页面的网址是:
url(r'^$',TemplateView.as_view(template_name="index.html"),name="index")
加载前:
加载页面后:
驾驶室有人帮助我。
答案 0 :(得分:0)
您是否尝试按下按钮重新加载页面并将您带到联系页面?如果是这样,您将收到404错误,因为您的应用正在尝试访问您的网址格式中不存在的/ contactus。如果您希望该网址返回404以外的任何内容,则需要将该条目添加到urls.py中
你可以在urls.py的行下方放置
...
url(r'^$',TemplateView.as_view(template_name="index.html"),name="index"),
url(r'^contactus', TemplateView.as_view(template_name='contactus.html'), name='contactus'),
...
然后为contactus.html
制作模板如果您希望将/ contactus的文本加载到页面中而不进行刷新,则可以通过更改contactus视图以返回JSON响应来返回您要插入到文档中的HTML。
class ContactUsView(View):
def get(self, request, *args, **kwargs):
contact_html = render(request, 'contactus.html', {})
return JsonResponse({'contact_html': contact_html})
无论哪种方式,404背后的原因是你没有告诉django你想从/ contactus端点返回什么数据。
答案 1 :(得分:0)
我还在app.routing.ts中使用了 {useHash:true} 的解决方案,它允许在网址中使用“#”并且工作正常。
@NgModule({
imports: [ RouterModule.forRoot(routes, { useHash: true }) ],
exports : [RouterModule]
})
答案 2 :(得分:0)
我找到了两个相同的解决方案
在这种方法中,您要做的是
urls.py
url(r'^$', views.index, name='home'), // Renders index page
url(r'^(?P<path>.*)/$', views.index), //handles other pages using django query params
view.py
def index(request, path=''):
"""
Renders homepage and handles other pages
"""
return render(request, 'index.html')
因此,此方法对索引页面的作用是仅呈现index.html,如果重新加载页面,则将请求发送到django,而django只需在保留当前路由的情况下再次再次加载index.html,但加载index.html意味着加载整个应用程序是因为angular是单页应用程序,而加载整个页面则是一个缺点
此方法仅使用哈希位置策略进行路由,路由使用哈希完成
app.modules.ts(或app.routing.module.ts)
@NgModule({
imports: [
//Other Modules
RouterModule.forRoot(routes, { useHash: true })
],
因此它将呈现http://127.0.0.1:8000/#/home
此解决方案是最好的示例,您可以使用Django查询参数或哈希位置策略在django-angular(v7)应用中处理页面刷新条件下未找到的页面404
Django Way Reference 角度方式Reference 2