从另一个模型中提取并保存数据

时间:2017-09-17 14:55:54

标签: django django-models django-authentication

在我的应用中,用户创建一个项目,然后创建一个团队并通过向他们发送邮件来邀请团队成员注册该应用。 我试图找出如何将受邀用户添加到之前创建的团队。 我尝试使用:TeamMember.user = user但显然它不起作用;) 你能帮我把它弄好吗?

注册/ views.py:

def TeamRegister(request):
    if request.method == 'POST':
        form = TeamMembersForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            password = MyUser.objects.make_random_password()
            user.set_password(password)
            user.is_active = False
            user.is_employee = True
            TeamMember.user = user
            user.save()
            u1 = user.id
            a1 = MyUser.objects.get(email = request.user.email)
            a2 = Project.objects.filter(project_hr_admin = a1)
            a3 = a2.latest('id')
            a4 = a3.team_id
            a4.members.add(u1)
            current_site = get_current_site(request)
            message = render_to_string('acc_active_email.html', {
                'user':user,
                'domain':current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
            mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            return HttpResponse('An email have been sent to your user asking him to sign in')

    else:
        form = TeamMembersForm()

    return render(request, 'team_register.html', {'form': form})

app / models.py

class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")


    def __str__(self):
        return self.team_name


class Project(models.Model):
    name = models.CharField(max_length=250)
    team_id = models.ForeignKey(Team, blank=True, null=True)
    project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)

    def get_absolute_url(self):
        return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:0)

您还需要以某种方式识别团队。如果您在视图中有团队,那么您可以只创建TeamMember对象:

# Just one suggestion of how this could be done, but this shouldn't work out of the box
TeamMember.objects.create(user_id=user.id,
                          team_id=Team.objects.get(id=form.cleaned_data['team_id'])) 

至于你的模型,查阅关于Django中M2M关系的Django文档:https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/

创建ManyToManyField并使用TeamMember作为through模型或删除它,因为Django也会自动生成它。