动态表单生成

时间:2011-06-11 22:11:04

标签: python django django-forms

我有一个活动邀请模型:

class EventInvitation(models.Model):

    from_user = models.ForeignKey(User, related_name="inviters")
    to_user = models.ForeignKey(User, related_name="invited")
    text = models.CharField(max_length= 150)
    event = models.ForeignKey(Event)
    sent = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=INVITATION_STATI, default=0)

我想要完成的是拥有一个动态邀请表单(不是ModelForm),其中邀请者有一组用户,基于该特定用户可以邀请的查询/人员,以及一组选择,也基于一个查询(邀请者必须是该组的所有者)...由于EventInvitation是针对单个用户,我将遍历所选用户和该组的成员并为所有人创建单独的邀请他们。知道如何生成这种动态形式吗?

1 个答案:

答案 0 :(得分:3)

据我了解,您想要一个登录用户,从活动页面点击“邀请其他人”按钮,向他显示一个表单,在那里他可以选择特定用户和组,指定一些文本,然后单击“发送”。然后,您的应用应该创建许多邀请实例(每个用户一个)并发送它们,跟踪邀请状态。如果这是正确的,我的建议是:

使用以下模型可以让您更好地控制数据(仅保留文本一次,并允许您查找所有用户以获取特定邀请):

class EventInvitation(models.Model):
    inviter = models.ForeignKey(User, related_name="inviters")
    event = models.ForeignKey(Event)
    text = models.CharField(max_length= 150)
    created = models.DateTimeField(auto_now=True)

class EventInvitationInvitee(models.Model):
    event_invitation = models.ForeignKey(EventInvitation)
    user = models.ForeignKey(User, related_name="invited")
    status = models.IntegerField(choices=INVITATION_STATI, default=0)

使用这样的简单表格:

from django.contrib.auth.models import User, Group

class InviteForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea)
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all())
    groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all())

    def __init__(self, user, *args, **kwargs):
      super(InviteForm, self).__init__(*args, **kwargs)
      self.fields['users'].queryset = User.objects.filter( ... )
      self.fields['groups'].queryset = User.objects.filter( ... )

...替换为您的代码,以过滤正确的群组和用户。

以这种方式观点:

def invite(request, event_id):
    event = get_object_or_404(Event, pk=event_id) # you can check if your user is allowed to access this event here
    if request.method == 'POST':
        form = InviteForm(request.user, request.POST)
        if form.is_valid():
            invitation = EventInvitation.objects.create(inviter=request.user, event=event,  text = form.cleaned_data['text'])
            users = set()
            for user in form.cleaned_data['users']:
                users.add(user)
                EventInvitationInvitee.objects.create(event_invitation=invitation, user=user)
            for group in form.cleaned_data['groups']:
                for user in group.user_set.all():
                    if user not in users:
                        users.add(user)
                        EventInvitationInvitee.objects.create(event_invitation=invitation, user=user)
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = InviteForm(request.user)

    return render_to_response('invite.html', {'form': form})

更新:您还可以使用更加pythonic的方式创建动态表单:

def get_invite_form(user):

  class InviteForm(forms.Form):
      text = forms.CharField(widget=forms.Textarea)
      users = forms.ModelMultipleChoiceField(queryset= ... )
      groups = forms.ModelMultipleChoiceField(queryset= ... )

  return InviteForm

使用user参数将...替换为查询集,稍后使用get_invite_form(request.user)(request.POST)get_invite_form(request.user)()代替InviteForm()