我有一些奇怪的事情,我似乎无法破解。我正在使用Tastypie构建API,当我在浏览器中针对localserver发出此调用时,它可以正常工作:localserver / api / v1 / userfavorite /?user__username = testowner
但是,在我的代码中,我收到错误:" int()参数必须是字符串或数字,而不是' SimpleLazyObject'"。我意识到它与被视为request.user对象的用户有关,但我无法弄清楚在哪里/为什么。我很困惑,为什么它在浏览器中发出API调用时有效,但在代码中它不起作用。
这是我的代码:
# views.py
@login_required
def favorites(request):
'''
display a list of posts that a user has marked as favorite
'''
user = request.user
favorites_url = settings.BASE_URL + "/api/v1/userfavorite/?user__username=" + user.username
favorites = get_json(favorites_url)
return render(request, "maincontent/favorites.html", {'favorites':favorites})
# resources.py
class UserFavoriteResource(ModelResource):
'''
manage post favorites by a user. Users can use a favorites list
to easily view posts that they have liked or deemed important.
'''
user = fields.ForeignKey(UserResource, 'user')
post = fields.ForeignKey('blog.api.resources.PostResource', 'post', full=True)
class Meta:
queryset = UserFavorite.objects.all()
allowed_methods = ['get', 'post', 'delete']
authentication = Authentication()
authorization = Authorization()
filtering = {
'user':ALL_WITH_RELATIONS
}
def hydrate_user(self, bundle):
# build the current user to save for the favorite instance
bundle.data['user'] = bundle.request.user
return bundle
def get_object_list(self, request):
# filter results to the current user
return super(UserFavoriteResource, self).get_object_list(request)\
.filter(user=request.user)
# utils.py
def get_json(url):
# return the raw json from a request without any extraction
data = requests.get(url).json()
return data
一些注意事项:
1.我有post方法工作来创建UserFavorite项目
2.我可以验证favorite_url是否正确生成了
我也试过硬编码favorites_url,同样的错误。
编辑:4。我在执行此操作时已登录,并已验证request.user返回用户
答案 0 :(得分:0)
这不起作用,因为request.user
中有匿名用户。您正在使用Authentication
它不需要用户登录。因此,如果您执行请求调用该请求未经过身份验证且request.user
是AnonymousUser,并且当您尝试将匿名用户保存到db时会发生该错误。 Tastypie
文档建议不使用浏览器进行测试,而只是卷曲。浏览器存储了大量数据,您可能会记得您已经记录到localhost:8000中的管理面板,这是另一个选项卡,这就是它在浏览器中工作的原因。
我更喜欢这样的事情:
def hydrate_user(self, bundle):
"""\
Currently logged user is default.
"""
if bundle.request.method in ['POST', 'PUT']:
if not bundle.request.user.is_authenticated():
raise ValidationError('Must be logged in')
bundle.obj.user = bundle.request.user
bundle.data['user'] = \
'/api/v1/userauth/user/{}'.format(bundle.request.user.pk)
return bundle