Informing Users with django.contrib.messages

The messages framework can be bit confusing to wrap your head around at first. Learn the basics of setting successful and error messages and show them to users. See the default django way, then see how to do with django-braces.

resources

Messages Framework

accounts/views.py

class LoginView(FormView):
    template_name = 'accounts/login.jinja'
    form_class = AuthenticationForm
    success_url = reverse_lazy('dashboard')

    def form_valid(self, form):
        user = form.get_user()
        auth_login(self.request, user)
        messages.add_message(
               self.request, messages.SUCCESS, 'Logged in Successfully')
        return super(LoginView, self).form_valid(form)

    def form_invalid(self, form):
        response = super(LoginView, self).form_invalid(form)
        messages.error(
            self.request, 'Username or Password invalid. Please try again')
        return response

accounts/views.py

class LoginView(FormMessagesMixin, FormView):
    template_name = 'accounts/login.jinja'
    form_class = AuthenticationForm
    success_url = reverse_lazy('dashboard')
    form_valid_message = 'Thank you for registering'
    form_invalid_message = 'Something went wrong. Please Try Again'

    def form_valid(self, form):
        user = form.get_user()
        auth_login(self.request, user)
        return super(LoginView, self).form_valid(form)
comments powered by Disqus