0

我正在使用 sweetpie 为我的 django 项目快速创建一个 api。我的 Django 由一些模型组成,其中一个是客户模型。客户模型对 django 的用户模型有一个外键,所以它看起来像这样

class Customer(models.Model):
    ...fields....
    creator = models.ForeignKey(User, related_name='created_customers'

我已经创建了我的 CustomerResource

class CustomerResourse(ModelResource):
    creator = fields.ForeignKey(UserResource,'creator', null = True,
        blank= True, full=True)
    class Meta:
        queryset = Customer.objects.all()
        filtering = {
            'last_name':ALL,
            'first_name':ALL,
    }
        resource_name = 'customer'
        authentication = SessionAuthentication()
        authorization = DjangoAuthorization()

我希望能够使用 api 更新我的模型。阅读教程,它说更新模型正在使用 PUT。所以我的步骤是。

1)登录并获取 sessionid 2)存储它 3)获取我需要的资源 4)修改我需要的资源 5)创建标头 6)使用 requests.put 将数据放回传递标头和 sessionid cookie。

代码(使用请求)

headers = {'content-type':'application/json'}
resp = requets.post(login_url, data=credentials, headers=headers)
sessionid = resp.cookies['sessionid']
cookies = {'sessionid':sessionid}
customer_json = request.get(customer_resource_url, cookies=cookies)
customer_json['mobile'] = 'new mobile'
resp.put(customer_resource_url, data=data, headers=headers, cookies=cookies)

我得到的是一个 401 未经授权的状态码。用户是超级员工,因此他可以修改所有内容。登录正常进行,我得到了我应该得到的 sessionid。

还有第二个问题。如果我创建一个新客户,tastepie 会处理外键,例如考虑 sessionid 来确定用户创建者,还是需要手动完成?

4

0 回答 0