【问题标题】:Why does django return the data I submitted as the HttpResponse?为什么django将我提交的数据作为HttpResponse返回?
【发布时间】:2020-08-31 15:10:05
【问题描述】:

所以我正在制作 Angular 8 和 Django 项目。场景是从 Angular 中的表单,数据被发送到 Django 以将其存储在数据库中。

class NewProfileView(viewsets.ModelViewSet):
    queryset = NewProfile.objects.all()
    serializer_class = NewProfileSerializer

    def post(self,request,*args,**kwargs):
        email = request.data['email']
        password = request.data['password']
        username = request.data['username']
        NewProfile.objects.create(email=email,password=password,username=username)
        return HttpResponse({'message':'Registered Successfully'},status=200)

以上代表我的 Django 视图。现在,看到这一点,为了成功创建,我应该将response 设为“已成功注册”。但是我得到的是我提交的JSON格式的数据(基本上是一个字典。我真的不知道是不是json)。

为什么会这样?

export class PostService {

  private url = 'http://localhost:8000/login/';

  constructor(private httpClient:HttpClient) {}

   getPosts(data){
      return this.httpClient.get(this.url+'?email='+data.email+'&password='+data.password);
    }

    create(url,post){
      return this.httpClient.post<any>(url,post);
    }
}

这就是我的 Angular 服务中的内容。

onSubmit(){
    console.log(this.userForm);
    this.service.create('http://localhost:8000/profile/',this.userForm)
        .subscribe(response=>{
            console.log(response);
        });

这是我的component.ts 文件中的代码。

P.S.- 我知道我存储密码的方式错误。但它只是用于调试目的。

【问题讨论】:

    标签: python django angular django-rest-framework


    【解决方案1】:

    要从 Django 返回字典数据,应该使用JsonResponse。这会将 Dict 序列化为 json 并添加正确的 Content-Type 标头。

    from django.http import JsonResponse
    >>> response = JsonResponse({'foo': 'bar'})
    >>> response.content
    >>> b'{"foo": "bar"}' # This will be the body sent to the client
    # In your Case
    >>> return JsonResponse({'message':'Registered Successfully'},status=200)
    

    在 Javascript 方面,您访问 JSON 数据的方式会因您用于进行 http 调用的客户端而异。您可以使用 JSON.parse(body) 解析响应正文,但我使用的大多数 http 客户端都会为您处理(Fetch API 有一个 response.json() 方法,我认为当响应为 json 类型时,axios 会自动为您提供 JS 对象)

    Dict 与 JSON 的注意事项

    我提交的JSON格式的数据(基本上是一个字典。我真的不知道是不是json)。

    Dictionary 是一种原生的 Python 类型。看起来类似于 JSON,但它们不一样。例如。 Python 使用 None,而 JSON 使用 null,还有许多其他类似的区别。

    JSON (Javascript Object Notation) 是一种序列化和反序列化 javascript 对象的方法。

    要将字典数据作为 JSON 对象发送到您的 JS 客户端,您需要 json.dumps(dict) 获取字典的序列化 json 版本,然后在响应正文中返回它。 JsonResponse 为您处理序列化,并添加“Content-Type”标头“application/json”,让您的客户端知道它正在接收可以反序列化为 JS 对象的 json 主体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多