我得到一个奇怪的问题。我正在创建一个将朋友添加到列表的函数,这是我的观点和网址。
@login_required(login_url='user:login')
def friend_add(request, friend):
friendship = FriendShip(
from_friend=request.user,
to_friend=friend
)
friendship.save()
return HttpResponseRedirect(request.path)
url(r'^add_friend/$', views.friend_add, name="add_friend"),
当我调用模板中的 url 时:
<input type="button" class="btn btn-info" value="Add Friend" onclick="location.href='{% url 'user:add_friend' friend=post.poster %}';">
加载网页时会发生异常:
对于"add_friend",未找到关键字参数"{'friend":}",则相反。 尝试了 1 种模式: ['用户/add_friend/$']
多次尝试后,可以加载网页,并删除输入
<input type="button" class="btn btn-info" value="Add Friend" onclick="location.href='{% url 'user:add_friend'%}';">
(这很奇怪,因为视图要求输入(
但是,当我单击该按钮时,发生了另一个异常:
friend_add(( 缺少 1 个必需的位置参数:"朋友">
我对这个问题感到非常困惑。非常感谢任何帮助!
注意:
path(..)
可从 Django-2.0 获得。
这里的问题是friend
不在 URL 中:
url(r'^add_friend/$', views.friend_add, name="add_friend"), # no parameter
例如,您可以通过指定path(..)
来使用好友的主键(pk
(:
path(r'add_friend/<int:friend>/', views.friend_add, name="add_friend"),
如果你使用 django-1.x,你可以将url(..)
与正则表达式一起使用:
url(r'^add_friend/(?P<friend>[0-9]+)/$', views.friend_add, name="add_friend"),
现在我们可以在反向网址中使用好友的主键:
<input
type="button"
class="btn btn-info"
value="Add Friend"
onclick="location.href='{% url 'user:add_friend' friend=post.poster.pk %}';"
>
(多行以使其更易于阅读(。
你的urlpattern shoul也有这样的朋友参数:
url(r'^add_friend/(?P<friend>[0-9]+)/$', views.friend_add, name="add_friend"),
这将允许您将朋友对象的整数 id 传递给 url,就像这样add_friend/12
。
data-ajax-target 在 HTML 按钮中调用 Django 的特定 URL
<button type="Submit" value="Submit" class="btn btn-outline-light text-dark" data-ajax-target="{% url 'collections' %}?collection={{ collection.collectionID }}" }">
<span>{{ collection.choice_label }}</span>
</button>