tags:

views:

38

answers:

1

I have a classroom application,and a follow relation. Users can follow each other and can create classrooms.When a user creates a classroom, he can invite only the people that are following him. The Classroom model is a m2m to User table.

i have in models. py:

class Classroom(models.Model):
     creator = models.ForeignKey(User)
     classname = models.CharField(max_length=140, unique = True)
     date = models.DateTimeField(auto_now=True)
     open_class = models.BooleanField(default=True)
     members = models.ManyToManyField(User,related_name="list of invited members")

and in models.py of the follow application:

class Relations(models.Model):    
    initiated_by = models.ForeignKey(User, editable=False)
    date_initiated = models.DateTimeField(auto_now=True, editable = False)
    follow = models.ForeignKey(User, editable = False, related_name = "follow") 
    date_follow = models.DateTimeField(auto_now=True, editable = False)

and in views.py of the classroom app:

def save_classroom(request, username):

   if request.method == 'POST':
        u = User.objects.get(username=username)
        form = ClassroomForm(request.POST, request.FILES) 
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.creator = request.user 
           r = Relations.objects.filter(initiated_by = request.user)
         #  new_obj.members = 
           new_obj.save()
           return HttpResponseRedirect('.')    
   else:
           form = ClassroomForm()     
   return render_to_response('classroom/classroom_form.html', {
           'form': form,

           }, 
          context_instance=RequestContext(request))  

i'm using a ModelForm for the classroom form, and the default view, taking in consideration my many to many relation with User table, in the field Members, is a list of all Users in my database. But i only want in that list the users that are in a follow relationship with the logged in user - the one who creates the classroom. How can i do that?

p.s: also, when i'm saving the form, it saves, but without "members"

Thanks!

+1  A: 

You have to change the queryset that is used to populate the formfield... Put the following in your form class:

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(ClassroomForm, self).__init__(*args, **kwargs)
        relations = Relations.objects.filter(initiated_by=user)
        self.fields["members"].queryset = \
            User.objects.filter(pk__in=[r.follow.pk for r in relations])

To get the current user into the form's __init__ method, change its initsialisation in your save_classrom view:

        form = ClassroomForm(request.POST, request.FILES, user=request.user) 
        # and after the else:
        form = ClassroomForm(user=request.user)     

I'm not quite sure about the query to get the users for your field, but i think it should be checked that initiated_by is the logged in user?

To save the m2m relations you also have to call form.save_m2m()!

lazerscience
yes, initiated_by should be the currently logged in user. thanks so much for the answer. i'll try this way right now
dana
Well as i said, I'm not totally sure about the query, but I think if i get it right getting the relations for this user and then taking the user that are then there in the "follow" relation should be the right way? YOu should also use no spaces in the related name (use an underscore instead). And the related name for "follow" should probably more something like "relations" (so that user.relations.all() will return all of his relations)?
lazerscience
anyways, i'm having a weird error: first, i've added request as a parameter in def __init__, for other way request.pop('user') wasn't recognised. But now, even though i'm including after that 'else' in the view form = ClassroomForm(user=request.user), it gives me the error : __init__() takes at least 2 non-keyword arguments (1 given)
dana
sorry my fault, should have been user = kwargs.pop('user') of course...
lazerscience
and then, how can i define the currently logged in user, so that in in init it will recognise my : initiated_by=user?thanks!
dana
I edited the example above, actually it should work as it is right now! If not tell me what the problem is!
lazerscience
I've edited just as above, and now it shows an error page with the mesage: "KeyError at /classroom/save_classroom/ user" p.s user is the text of the error, but i cannot insert carriage returns into comments. May the error be cause of that pop?Thanks so much for your interest!
dana
Do you still initialize the forms as i mentioned to do it? then there should be a key user in kwargs....ps. if you're lost with that and here's not too much room find me on skype with the same nick..
lazerscience
thanks so much, it works, i was mistaking the form init, just as you said. i'll also install skype (i'm using Ubuntu, and i'll try to find a similar program for it) and add you. also, i'm nicula_dana on YM, Twitter, and FB. thanks again!
dana