get current user in Django Form [duplicate]
Asked Answered
D

1

37

Possible Duplicate:
get request data in Django form

There's part of my Guest Model:

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

Form to get the response from the Guest:

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

The problem is in save method. How can I associate guest with the currently logged in user?

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

Instead of user=1 I need to have id of the currently logged in user.

Thank you!

Dinsdale answered 25/2, 2011 at 16:45 Comment(0)
D
57

I found the way :)

  1. Write a __init__ method on the form :
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(RSVPForm, self).__init__(*args, **kwargs)
  1. Change view function, and pass request.user to the form
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))
  1. the line of the save() method would look like this now:
guest = self.guest_class.objects.get(user=self.user)
Dinsdale answered 25/2, 2011 at 20:1 Comment(1)
Take care, you broke Liskov substitution principle: en.wikipedia.org/wiki/Liskov_substitution_principle . Look at this answer to add user parameter without break liskov principle: https://mcmap.net/q/426524/-django-how-to-access-current-request-user-in-modelformMaher

© 2022 - 2024 — McMap. All rights reserved.