Search code examples
djangodjango-viewsdjango-authentication

Handling user registrations Using only Django without the need to be redirected to other template


This is my view

class UserRegistrationView(FormView):
    template_name = "register/register_form.html"
    form_class = None
    extra_fields_form_page_slug = ""
    email_template = "register/account_activation_email.html"

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        add_extra_fields(
            form.fields, form.helper.layout.fields, self.extra_fields_form_page_slug
        )
        return form

    def get_extra_form(self):
        return FormPage.objects.filter(slug=self.extra_fields_form_page_slug).first()

    def form_valid(self, form):
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        email = form.cleaned_data.get("email")
        email_template = "register/account_activation_email.html"

        send_confirmation_email(
            self, "Activate Your  Account", user, email, email_template
        )
        return render(self.request, "register/after_submission.html")

This is working fine (registration wise) but it's not from many other sides, because I have the registration form as a pop up window in the header, so it's available throughout the whole website, my problems are:

  1. if the user had a successful registration they will be redirected to the specified template "after_submission" what I want is to stay on the same page and display a pop up with some message
  2. if the user had an unsuccessful registration they will be redirected to the main template "register_form.html" with the errors displayed their, what I want is to stay on the same page and to display the error messages on the pop up form if the user opened it again

is this achievable using only Django?? or I must throw some JS in there, and if JS is the answer, can you give me a quick insight into how to do it?


Solution

  • You can redirect to the same page in your CBV :

    from django.http import HttpResponseRedirect
    
    
    return HttpResponseRedirect(self.request.path_info)
    

    As stated in the comment your solution require Ajax and JS, you can however redirect to the same page but that will make a new request and refresh the whole page which might no be ideal for you.

    There is a tutorial to work with Django and Ajax Ajax / Django Tutorial