【发布时间】:2021-02-18 19:33:54
【问题描述】:
我尝试在 Django 中构建跟随系统,它显示字段 'id' 需要一个数字,但得到了 ''。如何获取我授予的当前profile用户的pk。
这是我的看法
def follow_unfollow_profile(request, **kwargs):
if request.method == 'POST':
my_account = Account.objects.get(username=request.user)
pk = request.POST.get('account_pk')
obj = Account.objects.get(pk=pk)
if obj.username in my_account.following.all():
my_account.following.remove(obj.username)
else:
my_account.following.add(obj.username)
return redirect(request.META.get('HTTP_REFERER'))
这是网址
path('<int:user_id>/', account_view, name="view"),
path('follow/', follow_unfollow_profile, name='follow-unfollow-view'),
我尝试获取对象pk的形式
<form action="{% url 'account:follow-unfollow-view'%}" method="POST">
{% csrf_token %}
<input type="hidden" name="account_pk" value={{account.pk}}>
<button type="submit" class="btn btn-success">Follow</button>
</form>
【问题讨论】:
-
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。
-
也许首先在浏览器的 HTML 中检查您在
form中的内容(即 Ctrl+U),然后在django中检查您在request.POST中获得的内容 - 也许您将空字符串发送到模板和浏览器得到value="",然后你在django中得到空字符串。生成此表单的函数在哪里?
标签: python django django-models django-views