views:

101

answers:

2

I'm using the pyfacebook module for Django to implement facebook Connect for one of my sites, I'm not using a local User object because I only want to use Facebook for login.

I understand that I can't access the request object from the save method on a Django form, so how would I access the facebook object that the provided middleware gives you?

I want to attach the users facebook UID to an object being created from a form, I could add it as a hidden field to the form but then people could just change it to make it appear that a question came from someone else.

What is the best way to pass in this uid to the save() method?

+2  A: 

You can set a variable on the form when you create it.

views.py

def myview(request):
    form = FacebookConnectForm(request)

forms.py

class FacebookConnectForm(forms.Form):
    def __init__(self, instance):
        self.instance = instance

    def save(self):
        print self.instance
        ...
Gattster
Since he will always need a request in the form I'd recommend making it an argument to the form __init__ . That way he would have to instantiate as in: form = FacebookConnectForm(request)
Flávio Amieiro
Good comment. I updated the answer.
Gattster
I don't think actually passing the request object into the form is the right thing to do, what if I need to use the form to edit the object later on? I won't have a request object to pass in.
Stuart Grimshaw
Where would you be using this form? I've never had a case for forms outside of my views, so there have always been request objects available.
Gattster
Stuart Grimshaw
good comment on coupling. I updated the answer.
Gattster
+1  A: 

The correct way to do this is to use an instance of the object you're trying to save, like this:

question = Question(user=int(request.facebook.uid))
form = QuestionForm(request.POST, instance=question)
question = form.save()
question.put()

Do this in your view, NOT in the save() method of your object.

Watch out if any of the fields are required though, you'll have to specify them in the instance objector calling form.save will throw an exception.

Stuart Grimshaw