python - How to get currently logged user id in form model in Django 1.7? -
let's have webpage displays songs. , let's there public , private songs. public songs available see, while private songs songs user has created , available him see. user should see songs owner_id == null , owner_id == currently_logged_in_user_id (his own id)
model:
import .... class song(models.model): name = models.charfield(max_length=100) duration = models.integerfield(max_length=15) owner = models.foreignkey(settings.auth_user_model, null=true, blank=true) def __unicode__(self): return self.name
view:
from django.shortcuts import render, redirect, get_object_or_404 django.contrib.auth.decorators import login_required songapp.models import song songapp.forms import songinfoform @login_required def song_info(request): song = get_object_or_404(box) song_status = song.get_status() form = songinfoform(initial={'song_list': song.song_list}) return render(request, 'songapp/song_info.html', {'form': form, 'song': song, 'song_status': song_status})
form:
django import forms django.forms import modelchoicefield songapp.models import song class songinfoform(forms.form): --> selected_songs = song.objects.filter(owner=none) | song.objects.filter(owner=3) song_list = modelchoicefield(queryset=selected_songs, required=false)
note line arrow in form file. problem lies. code works now,
(owner = 3)
is hardcoded. know fact users id 3. want work properly. should this:
(owner = currently_logged_in_user.id)
i'm still new django , python , don't know how pass users id songinfoform formmodel.
i've figured out.
in views.py change:
form = songinfoform(initial={'song_list': song.song_list}, user=request.user)
and answers before , example django form: passing parameter view.py forms gives out error i've came this, , works 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)
Comments
Post a Comment