动态表格生成

问题描述

| 我有一个活动邀请模型:
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)
我要完成的工作是创建一个动态邀请表单(NOT ModelForm),其中邀请者可以基于查询/可以由该特定用户邀请的人来选择用户,还可以选择一组基于在查询上(邀请者必须是组的所有者)...由于EventInvitation是针对单个用户的,因此我将遍历选定的用户和组的成员,并为所有这些人创建单独的邀请。知道如何生成这种动态表格吗?     

解决方法

        据我了解,您想要一个已登录的用户,在事件页面上,单击“邀请其他人”按钮,该按钮向他显示一个表单,他可以在其中选择特定的用户和组,指定一些文本,然后单击\ “发送\”。然后,您的应用应创建邀请的多个实例(每个用户一个)并发送它们,以跟踪邀请的状态。如果正确的话,以下是我的实施建议: 使用以下模型将为您提供对数据的更多控制(仅保留文本一次,并允许您查找所有用户以获取特定邀请):
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( ... )
用您的代码替换“ 3”以过滤正确的组和用户。 并以这种方式查看:
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})
更新:您还可以像下面这样以更Python化的方式创建动态表单:
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
使用用户参数用查询集替换
...
,然后使用
get_invite_form(request.user)(request.POST)
get_invite_form(request.user)()
代替
InviteForm()
。