據我瞭解,你要登錄的用戶,從活動頁面,點擊一個「邀請其他人」按鈕,這表明他的形式,在那裏他可以選擇特定的用戶和組,指定一些文本,然後點擊在「發送」上。然後,您的應用程序應創建許多邀請實例(每個用戶一個)併發送它們,以跟蹤邀請的狀態。如果這是正確的,我的建議如下:
使用以下模型可以讓您更好地控制數據(只保留一次文本,並允許您查找所有用戶的特定邀請):
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})
更新:
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
使用與查詢集替換...
:您也可以在這樣一個更Python的方式創建一個動態的形式用戶參數,以後使用get_invite_form(request.user)(request.POST)
和get_invite_form(request.user)()
而不是InviteForm()
。
來源
2011-06-12 12:38:30
Udi
我不明白你爲什麼不能使用窗體類的所有邀請。您可以爲每個表單實例提供一個不同的用戶列表供您選擇。 – 2011-06-11 23:43:09