我遇到了Django框架的问题。详细地,用户可以创建组并将该成员(> = 1&&< = 3)与该组相关联。每个成员都通过电子邮件地址(唯一)标识。但是,同一成员可以在不同的组中使用不同的名称和姓氏进行partecipate。所以我和Group之间有很多关系(使用)。 在我看来,我有一个inlineformset。但是,当我提交表格时,我总是得到:
archi_groupmember.group_id可能不是NULL
我已经更改了MemberGroup表单的小部件,因为用户不必从select中选择成员,但他必须键入成员的邮件。 所以我想我应该保留会员才能保存会员组,但我不知道怎么做!
我是Django的新手,我正在关注文档。
谢谢大家的帮助!!
此处的页面屏幕截图只是为了澄清:http://postimg.org/image/bndh5ug29/
关注我的代码。
Models.py:
class Group(models.Model):
user = models.ForeignKey(User)
limit = Q(active = True)
project = models.ForeignKey(Project, limit_choices_to = limit)
name = models.CharField(max_length=100)
code = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.name
class Member(models.Model):
groups = models.ManyToManyField(Group, through='GroupMember')
email = models.EmailField(max_length=254, unique=True)
def __unicode__(self):
return self.email
class GroupMember(models.Model):
group = models.ForeignKey(Group)
member = models.ForeignKey(Member)
name = models.CharField(max_length=100)
surname = models.CharField(max_length=100)
views.py:
@login_required
@user_passes_test(first_login_check, login_url='/detail')
def partecipate(request):
from django.forms import TextInput
MemberFormSet = inlineformset_factory(Group, Member.groups.through, form=GroupMemberForm, can_delete=False, extra=3, widgets={'member': TextInput() } )
if request.method == 'POST':
form = GroupForm(request.POST)
member_set = MemberFormSet(request.POST)
if form.is_valid():
for form in member_set:
print vars( form['member'] )
group = form.save(commit=False)
group.user = request.user
group.code = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
group.save()
member_set = MemberFormSet(request.POST, instance=group)
member_set = member_set.save(commit=False)
payment = Payment()
payment.group = group
payment.invoice = _createInvoice(group.project.id, group.id)
payment.save()
return HttpResponseRedirect("/")
else:
return render(request, "partecipate.html", { 'form': form, 'member_set' : member_set })
else:
form = GroupForm()
form.Meta.model.project.queryset = Project.objects.filter(active=True)
member_set = MemberFormSet(initial=[ {'name': request.user.first_name,'surname': request.user.last_name,'member':request.user.email} ])
return render(request, "partecipate.html", { 'form': form, 'member_set' : member_set })
答案 0 :(得分:0)
您使用的是什么版本的Django?
自1.3以来,帮助文档中有一个使用 inlineformset_factory 的示例。示例(下面的链接)清楚地显示了传递父记录的实例。没有它,您的表单集将不会链接到实际数据。
https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#using-an-inline-formset-in-a-view
我还怀疑将 Member.groups.through 表类指定为子级。我认为你应该把它留作会员,因为直通表是内部机制的一部分。