简洁版本:
我有一个用于食谱的 Django 应用程序,并且想要过滤要发送到我的视图中的模板的数据。我基本上希望特定用户添加的所有收据都作为上下文发送。以下过滤返回错误消息以 10 为基数的 int() 的文字无效:我的用户名.
recipes = Recipe.objects.filter(added_by = uname)
变量uname是从模板传递的。另一方面,过滤请求.用户工作正常,但不是我想要的。
recipes = Recipe.objects.filter(added_by = request.user)
Details:
我的模型给出(相关字段)为:
class Recipe (models.Model):
...
...
added_by = models.ForeignKey(User)
Where User是现有的 Django 用户。当我在模板中调用 {{recipe.added_by }} 时,我得到了想要的用户名。该用户名将传递到视图href="/profile/{{recipe.added_by}}",其中视图如下所示:
def profile(request, uname):
print uname #Correct username printed
print request.user #Logged in user (not relevant, as userprofile should be visible for all)
recipes = Recipe.objects.filter(added_by = uname) #Does not work. Why?
#recipes = Recipe.objects.filter(added_by = request.user)
form = CommentForm(request.POST)
context = {
'uname': uname,
'recipes': recipes,
'form': form,
}
return render(request, '*app_name*/profile.html', context)
不确定我错过了什么,但据我所知,这似乎与以下事实有关:added_by有一个用户的外键。我还尝试将过滤器参数更改为食谱__added_by__added_by = uname根据[1],但 Django 随后返回了一个错误,指出“无法将关键字‘recipe’解析为字段”,这似乎是显而易见的。我的网址是:
url(r'^profile/([a-zA-Z0-9]+)/$', 'profile', name='*app_name*-profile'),
感谢您的任何回复。抱歉,如果这应该是显而易见的。
[1] Django 模型通过外键过滤 https://stackoverflow.com/questions/11508744/django-models-filter-by-foreignkey