以Django Form获取当前用户

时间:2011-02-25 16:45:21

标签: django-forms django-users

  

可能重复:
  get request data in Django form

我的访客模型的一部分:

class Guest(models.Model):
    event = models.ForeignKey(Event, related_name='guests')
    user = models.ForeignKey(User, unique=True, related_name='guests')
    ...

表格以获得来宾的回复:

class RSVPForm(forms.Form):
    attending_d= forms.ChoiceField(choices=VISIBLE_ATTENDING_CHOICES, initial='yes', widget=forms.RadioSelect)
    attending_b = forms.ChoiceField(choices=VISIBLE_ATTENDING_CHOICES, initial='yes', widget=forms.RadioSelect)
    number_of_guests = forms.IntegerField(initial=0)
    comment = forms.CharField(max_length=255, required=False, widget=forms.Textarea)

    ....    

    def save(self):
        guest = self.guest_class.objects.get(user=1)
        guest.attending_status_d = self.cleaned_data['attending_d']
        guest.attending_status_b = self.cleaned_data['attending_b']
        guest.number_of_guests = self.cleaned_data['number_of_guests']
        guest.comment = self.cleaned_data['comment']
        guest.save()
        return guest

问题在于保存方法。如何将访客与当前登录的用户相关联?

guest = self.Guest.objects.get(user=1)

而不是user=1我需要拥有当前登录用户的ID。

谢谢!

1 个答案:

答案 0 :(得分:42)

我找到了方法:)

  1. 在表单上写一个__init__方法:

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(RSVPForm, self).__init__(*args, **kwargs)
    
  2. 更改视图功能,并将request.user传递给表单

    def event_view(request, slug, model_class=Event, form_class=RSVPForm,
                                    template_name='rsvp/event_view.html'):
        event = get_object_or_404(model_class, slug=slug)
    
        if request.POST:
            form = form_class(request.user, request.POST)
    
        if form.is_valid():
            guest = form.save()
            return HttpResponseRedirect(reverse('rsvp_event_thanks',
                        kwargs={'slug': slug, 'guest_id': guest.id}))
        else:
            form = form_class(request.user)
    
        return render_to_response(template_name, {
            'event': event,
            'form': form,
        }, context_instance=RequestContext(request))
    
  3. save()方法的行现在看起来像这样:

    guest = self.guest_class.objects.get(user=self.user)