Date: April 18th 2016
Last updated: April 18th 2016

Django has some built in forms. The PasswordChangeForm is one of them. One thing I took note of in this example is accessing user info from request rather than retaining an id in the url pattern that I would use later. Seems silly now, but it took the PasswordChangeForm to show me how to more effectively use request.

from django.conf.urls import url
from . import views

app_name = 'surferprofile'
urlpatterns = [
    url(r'^changepassword/$', views.change_password, name='changepassword'),
    #<- snipped ->

# load modules
from django.contrib.auth import update_session_auth_hash
from .forms import MyChangePasswordForm
from django.contrib import messages

def change_password(request):
    if request.method == 'POST':
        # note that MyChangePasswordFrom inherits from PasswordChangeForm
        # I have done this to use crispy forms
        form = MyChangePasswordForm(request.user, data=request.POST)
        if form.is_valid():
            update_session_auth_hash(request, form.user) # dont logout the user.
            messages.success(request, "Password changed.")
            # redirect to the users profile page which is an membership id
            return redirect('/{}/'.format(
        form = MyChangePasswordForm(request.user)
    data = {
        'form': form
    return render(request, "surferprofile/change_password.html", data)

# load modules
from django.contrib.auth.forms import PasswordChangeForm

class MyChangePasswordForm(PasswordChangeForm):
    def __init__(self, *args, **kwargs):
        super(MyChangePasswordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post' # this line sets your form's method to post
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-4'
        self.helper.field_class = 'col-lg-6'
        self.helper.form_tag = False
        self.helper.add_input(Submit('submit', u'Submit'))


{% load staticfiles %}
{% load crispy_forms_tags %}

      <link rel="stylesheet" type="text/css" href="{% static 'surferprofile/style.css' %}" />
      <link rel="stylesheet" href="">
      <link href='' rel='stylesheet' type='text/css'>
      <script src=""></script>
      <script src=""></script>

    <div id = "formcontainer">
        <h1 style="text-align: center;">Change password</h1>
        <form id='changepassword' role="form" action="" method="post">
            {% csrf_token %}
            {% crispy form %}

results matching ""

    No results matching ""