[Django]-How do I successfully pass variables to my python social auth pipeline?

0👍

Here’s the most common approach… start by creating a partial pipeline named pipeline_user_plan.py in one of your Django apps

from django.shortcuts import redirect
from social_core.pipeline.partial import partial

@partial
def require_user_plan_step(
    strategy, backend, details, request, *args, is_new=False, **kwargs
):
    user_plan = strategy.session_get("user_plan", None)
    if is_new and not user_plan:
        request.session["backend"] = backend.name
        return redirect("require_user_plan_view")
    return None

In your settings.py

SOCIAL_AUTH_FIELDS_STORED_IN_SESSION = [
    "backend",
    "user_plan",
]
SOCIAL_AUTH_PIPELINE = (
    ...
    "myapp.pipeline_user_plan.require_user_plan_step",
    ...

That assumes in your urls.py you have

re_path(
    r"^require-user-plan-view/$",
    views.require_user_plan_view,     
    name="require_user_plan_view",
),

Then in your views.py

def require_user_plan_view(request):
    if request.method == "POST":
        request.session["user_plan"] = request.POST["user_plan"]
        backend_name = request.session["backend"]
        return redirect(reverse("social:complete", args=(backend_name,)))
    form = UserPlanForm()
    return render(request, "require-user-plan-form.html", {"form": form})

which require a forms.py like

from django import forms

class UserPlanForm(forms.Form):
    user_plan = forms.ChoiceField(widget=forms.RadioSelect)

and a template require-user-plan-form.html

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" class="btn btn-neutral" id="submit" value="Submit" />
</form>

Leave a comment