【问题标题】:Django Page Error 404 - Loading JSON via uriDjango 页面错误 404 - 通过 uri 加载 JSON
【发布时间】:2020-05-11 21:51:24
【问题描述】:

您好,我正在开发一个 React Frontend - Django rest 框架,将 API 用作后端。当我加载模型时,它返回此错误 404。我不确定如何将 /models 包含在 urls.py 中,以便能够加载 .json 文件。我可以使用 Media_URL 或 static_URL 来提供 json 文件吗?

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/models/movies.json
Using the URLconf defined in movieproject.urls, Django tried these URL patterns, in this order:


^api/movies/$ [name='movies-list']
^api/movies\.(?P<format>[a-z0-9]+)/?$ [name='movies-list']
^api/movies/(?P<pk>[^/.]+)/$ [name='movies-detail']
^api/movies/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='movies-detail']
^$ [name='api-root']
^\.(?P<format>[a-z0-9]+)/?$ [name='api-root']
The current path, models/movies.json, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您可以通过使用 Django 的HttpResponse 的后端代码来做到这一点。

    urls.py

    url(r'^(?P<file_name>[\w]+).json$', views.loadjson, name='loadjson')
    

    views.py

    from django.http import HttpResponse
    
    def loadjson(request, file_name):
        json_file = "/path/to/json/" + file_name + ".json"
        json_content = read_file(json_file)
        return HttpResponse(
            json_content,
            content_type='application/json',
            status=200
        )
    

    注意:不要忘记将/path/to/json/ 编辑到json文件的目录路径。

    这对你应该没问题。

    【讨论】:

    • 嗨 Astik,我仍然收到错误 404,我是否需要将此 /models/ 文件夹包含在 settings.py 中的某处?
    • 你需要把你的json文件放在static目录下,然后在views方法的代码中给出该目录的路径。
    • 谢谢!它有效:) 抱歉,我没有时间研究它。但我测试过,它运行良好。
    • @Arbitel,很高兴这有帮助。
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2017-12-17
    • 2013-10-03
    • 2012-02-23
    • 2012-08-11
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多