[Django]-How to get currently logged user id in form model in Django 1.7?

5👍

I’ve figured it out.

In views.py change:

form = SongInfoForm(initial={'song_list': song.song_list}, user=request.user)

And thanks to the answers before and this example
django form: Passing parameter from view.py to forms gives out error
I’ve came up with this, and it works like a charm.

In forms.py

class SongInfoForm(forms.Form):
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(SongInfoForm, self).__init__(*args, **kwargs)
        self.fields['song_list'] = forms.ModelChoiceField(queryset=Song.objects.filter(owner=None) | Song.playlist.objects.filter(owner=user), required=False)

0👍

OK, my bad. Didn’t read enought to see problem lies in the form, But according to this post: https://stackoverflow.com/a/5122029/2695295 you could rewrite your for like this:

class SongInfoForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(SongInfoForm, self).__init__(*args, **kwargs)

    selected_songs = Song.objects.filter(owner=None) | Song.objects.filter(owner=user.id)
    song_list = ModelChoiceField(queryset=selected_songs, required=False)

and then in view create your form like this:

form = SongInfoForm(request.user, initial={'song_list': song.song_list})

this way form object should have access to user.

👤Dawid

Leave a comment