我添加了加入组功能,它运行正常。现在,但是,我试图添加离开组功能,这似乎是相似的,但它不起作用,也没有给我一个错误。这是加入和离开组的代码。应该注意的是,用户和组之间存在M2M关系。
(urls.py):
from . import views
from django.urls import path
app_name = 'groups'
urlpatterns = [
path('create/', views.create, name='create'),
path('index/', views.index, name='index'),
path('<int:group_id>/', views.detail, name='detail'),
path('<int:group_id>/join/', views.join, name='join'),
path('<int:group_id>/leave/', views.join, name='leave'),
]
(views.py):
def join(request, group_id):
group = get_object_or_404(Group, pk= group_id)
if request.method == 'POST':
group.members.add(request.user)
group.save()
return redirect('/groups/' + str(group_id) )
else:
return render(request, '/groups/detail.html', {'group': group})
def leave(request, group_id):
group = get_object_or_404(Group, pk= group_id)
if request.method == 'POST':
if request.user in group.members.all:
group.members.remove(request.user)
group.save()
return redirect('home')
else:
return render(request, '/groups/index.html')
基团/ detail.html
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-4">
<h1>{{group.name}}</h1>
</div>
<div class="col-6">
<p>{{group.description}}</p>
</div>
{% if user in group.members.all %}
<div class="col-2">
<a href="javascript:{document.getElementById('leave').submit()}"><button class="btn btn-primary btn-lg btn-block"> Leave {{product.members.count}}</button></a>
</div>
{% else %}
<div class="col-2">
<a href="javascript:{document.getElementById('join').submit()}"><button class="btn btn-primary btn-lg btn-block"> Join {{product.members.count}}</button></a>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-4">
<img src="{{group.image.url}}" alt="">
</div>
</div>
<br>
<br>
<div class="row bootstrap snippets">
<div class="col-md-3 container-widget">
<div class="panel panel-info panel-widget">
<div class="panel-title text-center">
Group Members
</div>
<div class="panel-body">
{% for member in group.members.all %}
<ul class="basic-list image-list">
<li><b>{{member.username}}</li>
</ul>
{% endfor %}
</div>
</div>
</div>
</div>
<form method ='POST' id= 'leave' action="{% url 'groups:leave' group.id %}" >
{% csrf_token %}
<input type="hidden" >
</form>
<form method ='POST' id= 'join' action="{% url 'groups:join' group.id %}" >
{% csrf_token %}
<input type="hidden" >
</form>
{% endblock %}
在此输入代码
答案 0 :(得分:0)
group.members.all
是一种方法,您需要调用它。
但不要这样做;它不必要地从数据库中查询所有成员。您可以使用exists()
,但实际上根本没有理由进行检查;如果项目不存在,则remove()
是无操作。只需打电话。
此外,修改多对多关系后,您不需要全部.save()
。
答案 1 :(得分:0)
您views.join
写了两次,第二个应该是views.leave