Django中间M2M a [href]没有将数据保存到数据库

时间:2017-12-03 16:39:15

标签: python django manytomanyfield

使用Django(社交平台)处理项目,用户可以在其中创建组以供其他用户加入或离开。

这是我的第一个Django项目,我不确定我的加入和离开组逻辑的实现是否正确。我有一个加入按钮,它是一个[href]标签:

<a href="{% url 'join' group.id %}" class="btn btn-primary">Join Group</a>

单击它应该将用户添加到组中。以下是模型和视图:

models.py:

@python_2_unicode_compatible
class Group(models.Model):
    title = models.CharField(max_length=255, null=False, unique=True)
    description = models.TextField(max_length=2000, null=False)
    location = models.CharField(max_length=255, null=False)
    date = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(User, related_name="creator")
    members = models.ManyToManyField(User, through='Membership')
    counter = models.IntegerField(blank=False, null=True)

@python_2_unicode_compatible
class Membership(models.Model):
    person = models.ForeignKey(User)
    group = models.ForeignKey(Group)
    date_joined = models.DateField(auto_now_add=True)

views.py:

@login_required
def group(request, pk):
    group = get_object_or_404(Group, pk=pk)
    return render(request, 'group/group.html', {'group': group})


@login_required
def join(request, pk):
    _group = get_object_or_404(Group, pk=pk)
    membership = Membership()
    membership.group = _group
    membership.person = request.user
    membership.save()
    return group(request, pk)

用户未保存到成员资格表。解决这个问题的最佳方法是什么?任何帮助将非常感谢。

还尝试了此连接按钮的视图功能:

@login_required
def join(request, pk):
    _group = get_object_or_404(Group, pk=pk)
    membership = Membership.objects.create(user=request.user, group=_group)
    membership.save()
    return group(request, pk)

网址:

urlpatterns = [
    url(r'^$', views.groups, name='groups'),
    url(r'^all/$', views.all, name='all'),
    url(r'^create_group/$', views.CreateGroup.as_view(), name='create_group'),
    url(r'^(\d+)/$', views.group, name='group'),
    url(r'^(\d+)/$', views.join, name='join'),
]

1 个答案:

答案 0 :(得分:0)

修正了问题。现在使用表格

List<List<Integer>> myList = new ArrayList<>();
List<Integer> x = new ArrayList<>();
x.add(5);
x.add(6);

List<Integer> y = new ArrayList<>();
y.add(5);
y.add(6);

myList.add(x);
myList.add(y);

加入网址是:

<form role="form" method="post" action="{% url 'join' %}" onsubmit="return true">
        {%csrf_token %}
        <input type="hidden" name="group_id" value="{{ group.id }}">
        <input type="submit" value="Join Group">