新记录与特定对象的关联

时间:2017-03-10 21:22:13

标签: python django python-3.x django-views

我有'project_list'和'project_detail'页面。在'project_detail'页面中,我有一个按钮,用户将用户重定向到'project_members'页面,在那里他们可以向当前项目添加新成员。如何将新创建的成员与当前项目相关联。我对视图有点困惑。什么是实现它的最好方法?

models.py

class Project(models.Model):
    ***FIELDS***
    members = models.ManyToManyField(User, through='Membership',)

ROLE_CHOICES = (
        ('manager', 'Manager'),
        ('developer', 'Developer'),
        ('business_analyst', 'Business analyst'),
        ('system_analysts', 'System analysts'),
)

class Membership (models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES,)

forms.py

class ProjectMembersForm(forms.ModelForm):
    class Meta:
        model = Membership
        exclude = ('project',)

    def __init__(self, *args, **kwargs):
        super(ProjectMembersForm, self).__init__(*args, **kwargs)
        self.fields['role'].choices = tuple(choice for choice in ROLE_CHOICES if choice[0] not in ['manager'])

urls.py

urlpatterns = [
    url(r'^project/(?P<slug>[-\w]+)/$', project_detail, name='project_detail'),

    url(r'^project/(?P<slug>[-\w]+)/members$', project_members, name='project_members'),
]

view.py

def project_members(request, slug):
    if slug:
        if request.method == 'POST':
            members_form = ProjectMembersForm(request.POST)
            if members_form.is_valid():
                members_form.save()
            else:
                members_form = ProjectMembersForm(instance=request.user)
            return render(request, 'project/project_members.html', {'members_form': members_form,})

1 个答案:

答案 0 :(得分:0)

最后我几天前找到了回答。您需要将此添加到 views.py

***
new_member = form.save(commit=False)
new_member.project = project  # Add this line
new_member.save()
***