Получить имя из Facebook с помощью django-socialregistration - PullRequest
2 голосов
/ 24 декабря 2011

С django-socialregistration что мне нужно сделать, чтобы получить имя от Facebook в момент подключения Facebook?

Я пытался поместить эти строки в django-socialregistration/views.py:

graph = request.facebook.graph 
fb_profile = graph.get_object("me")
user.first_name = fb_profile['first_name']
user.save()

в методе post(self, request) после user = profile.authenticate(), но я получаю эту ошибку при попытке подключения:

int() argument must be a string or a number, not 'AnonymousUser'

Почему?Ошибка возникает в первой строке graph = request.facebook.graph

Код представления django-socialregistration:

class Setup(SocialRegistration, View):
    """
    Setup view to create new Django users from third party APIs.
    """
    template_name = 'socialregistration/setup.html'

    def get_form(self):
        """
        Return the form to be used. The return form is controlled
        with ``SOCIALREGISTRATION_SETUP_FORM``.
        """
        return self.import_attribute(FORM_CLASS)

    def get_username_function(self):
        """
        Return a function that can generate a username. The function
        is controlled with ``SOCIALREGISTRATION_GENERATE_USERNAME_FUNCTION``.
        """
        return self.import_attribute(USERNAME_FUNCTION)

    def get_initial_data(self, request, user, profile, client):
        """
        Return initial data for the setup form. The function can be
        controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``.

        :param request: The current request object
        :param user: The unsaved user object
        :param profile: The unsaved profile object
        :param client: The API client
        """
        if INITAL_DATA_FUNCTION:
            func = self.import_attribute(INITAL_DATA_FUNCTION)
            return func(request, user, profile, client)
        return {}

    def generate_username_and_redirect(self, request, user, profile, client):
        """
        Generate a username and then redirect the user to the correct place.
        This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME``
        is set.

        :param request: The current request object
        :param user: The unsaved user object
        :param profile: The unsaved profile object
        :param client: The API client
        """
        func = self.get_username_function()

        user.username = func(user, profile, client)
        user.save()

        profile.user = user
        profile.save()

        user = profile.authenticate()

        self.send_connect_signal(request, user, profile, client)

        self.login(request, user)

        self.send_login_signal(request, user, profile, client)

        self.delete_session_data(request)

        return HttpResponseRedirect(self.get_next(request))

    def get(self, request):
        """
        When signing a new user up - either display a setup form, or
        generate the username automatically.
        """
        # I want some validation here, hacked up in the generic callback
        try:
            urlfrom = request.session['urlfrom']
            match = resolve(urlfrom)
            username, code = match.args
            checkcode, referrer, ticket = utils.register_validate(username, code)
        except:
            return http.HttpResponseServerError()
        # validation end

        try:
            user, profile, client = self.get_session_data(request)
        except KeyError:
            return self.render_to_response(dict(
                error=_("Social profile is missing from your session.")))

        if GENERATE_USERNAME:
            return self.generate_username_and_redirect(request, user, profile, client)

        form = self.get_form()(initial=self.get_initial_data(request, user, profile, client))

        return self.render_to_response(dict(form=form))

    def post(self, request):
        """
        Save the user and profile, login and send the right signals.
        """
        try:
            user, profile, client = self.get_session_data(request)
        except KeyError:
            return self.render_to_response(dict(
                error=_("A social profile is missing from your session.")))

        form = self.get_form()(request.POST, request.FILES,
            initial=self.get_initial_data(request, user, profile, client))

        if not form.is_valid():
            return self.render_to_response(dict(form=form))

        user, profile = form.save(request, user, profile, client)

        # validation count up referrals, tickets, etc.
        try:
            urlfrom = request.session['urlfrom']
            match = resolve(urlfrom)
            username, code = match.args
            checkcode, referrer, ticket = utils.register_validate(username, code)
        except:
            return http.HttpResponseServerError()
        utils.register_accounting(checkcode, referrer, ticket, user)

        user = profile.authenticate()

        self.send_connect_signal(request, user, profile, client)

        self.login(request, user)

        self.send_login_signal(request, user, profile, client)

        self.delete_session_data(request)

        # added by me
        graph = request.facebook.graph 
        fb_profile = graph.get_object("me")
        user.first_name = fb_profile['first_name']
        user.save()
        #

        return HttpResponseRedirect(self.get_next(request))

Ответы [ 2 ]

1 голос
/ 05 января 2012

Похоже, у вас может быть объект AnonymousUser в request.user при доступе к request.facebook.graph. Проверьте, если ваш пользователь is_authenticated (больше документов на AnonymousUser ):

request.user.is_authenticated()

Еще одна вещь, с которой можно поиграть - это pdb изнутри сервера разработки (manage.py runserver). Самый простой способ использовать его - использовать эту строку кода, чтобы поставить точку останова непосредственно перед тем, как ваш код будет запущен:

import pdb; pdb.set_trace()

Это даст вам подсказку, где вы можете посмотреть на переменные в контексте.

1 голос
/ 01 января 2012

позвольте мне нанести удар.Оттуда, где находится ваш код, он появляется прямо над ним, и вы убиваете сеанс self.delete_session_data(request).Это может убрать ключ сеанса или токен аутентификации.Попробуйте свой код выше этой строки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...