django API не работает с <form>, но работает в почтальоне - PullRequest
0 голосов
/ 03 марта 2020

Я пытаюсь загрузить возвращенный json из django API. Я тестировал на почтальоне, django API правильно показывает json, но когда я пытаюсь в моем html, он показывает

Код ошибки 501. Сообщение: может только POST to myapp Код ошибки объяснение: 501 = Сервер не поддерживает эту операцию.

views.py :

@csrf_exempt
def export_json(request):
    projectname = "resume"
    folderpath = "/home/user/mywebapp/data"
    if request.method == "POST":
        fullpath=os.path.join(folderpath,projectname)
        json_result=ann_json(fullpath)

        with open("json_file.json","w",encoding="utf-8") as jsonfile:
            json.dump(json_result,jsonfile)

        file1 = open("../json_file.json", "r",encoding="utf-8")
        response = HttpResponse(file1.read(),content_type="application/force-download")
        response['Content-Disposition'] = 'attachement; filename=%s' % smart_str("json_file.json")
        response['X-Sendfile'] = smart_str("myapp/project/json_file.json")

        return response

index. html :

<form action="http://127.0.0.1:8000/export_json" method="POST">
    <label class="optinLabel">Project Name</label>
    <input type="text" placeholder="confirm your project name"/>
    <label class="optionLabel">Downlaod</label>
    <input  type="submit" value="Json" style="color:red" />
</form>

<script>
    fetch('http://127.0.0.1:8000/export_json')
        .then((response) => return response.json())
        .then((data) => {
        localStorage.setItem("jsonfile",data)
    });
</script>

1 Ответ

0 голосов
/ 03 марта 2020

fetch установлен по умолчанию на метод GET. Судя по вашей ошибке, вы используете метод, отличный от POST для доступа к вашей конечной точке. Вручную установите свойство method правильно в настройках fetch.

fetch('http://127.0.0.1:8000/export_json', { method: 'POST' })
  .then((response) => return response.json())
  .then((data) => {
  localStorage.setItem("jsonfile",data)
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...