CH

October 7, 2016

Least-Effort Signups in Django

Filed under: django, magic, python, software development — Benjamin Vulpes @ 12:57 a.m.

It's wwwtronix hell weekmonthyeareternity at Cascadian Hacker!

Alonso complains:

No automatic login1 :(

So, have some Django-flavored Python that'll create, save and log your new users in2 in one swell foop:

class SignupForm(UserCreationForm):

    def save(self, commit=True):
        u = super(UserCreationForm, self).save(commit=False)
        u.is_active = True
        u.save()
        return u

class Signup(CreateView):
    model = User
    template_name = 'SOME_TEMPLATE'
    form_class = SignupForm
    success_url = "/"

    def form_valid(self, form):
        u = form.save()
        login(self.request, u)
        return HttpResponseRedirect("/")

There. That wasn't so hard now, was it?

  1. For context: the Django web framework provides some pre-baked forms and validators to handle new user signups. However, none of them go so far as to set the session cookie and tell the framework to "log the user in". That is what Alonso is complaining about. []
  2. The "activate my account" meme is just another step in your funnel in which potential customers will (at some statistical rate) fall out and hit the floor. You didn't need it, you're welcome. []

---