BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

16. Django 1.8 Server Build - CentOS 7 hosted on VPS - User Authentication 3 (password reset)

django.png




Bookmark and Share





bogotobogo.com site search:



password reset

In this tutorial, we want to allow a user to reset their password by generating a one-time use link that can be used to reset the password, and sending that link to the user's registered email address.

Using the Django authentication system

Actually, code (driver/templates/login.html) was there even though it's not fully implemented:

{% extends "base.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p>Please correct the following fields:</p>{% endif %}
<div class="register_div">
        {% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
        <p><label for="username"{% if form.username.errors %} class="error"{% endif %}>Username:</label></p>
        <p>{{ form.username }}</p>
</div>
<div class="register_div">
        {% if form.password.errors %}<p class="error">{{ form.password.errors }}</p>{% endif %}
        <p><label for="password"{% if form.password.errors %} class="error"{% endif %}>Password:</label></p>
        <p>{{ form.password }}</p>
</div>
<p><input type="submit" alt="register" /></p>
</form>
<p>Forgot your password? <a href="/resetpassword/">Reset it!</a></p>
{% endblock %}

We want to switch the base_site.html to base.html to customize the pages for other html pages as well.


reset-it-link.png




urls.py

This is our current file structure:

tree-templates-root.png

We'll add the following highlighted four urls to urls.py:

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
   url(r'^tinymce/', include('tinymce.urls')),
   url(r'^$', 'pages.views.MainHomePage'),
   url(r'^cars/$', 'car.views.CarsAll'),
   url(r'^cars/(?P<carslug>.*)/$', 'car.views.SpecificCar'),
   url(r'^makes/(?P<makeslug>.*)/$', 'car.views.SpecificMake'),
   url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
   }),
   url(r'^register/$', 'driver.views.DriverRegistration'),
   url(r'^login/$', 'driver.views.LoginRequest'),
   url(r'^logout/$', 'driver.views.LogoutRequest'),
   url(r'^resetpassword/passwordsent/$', 'django.contrib.auth.views.password_reset_done'),
   url(r'^resetpassword/$', 'django.contrib.auth.views.password_reset',
       {'post_reset_redirect' : 'django.contrib.auth.views.password_reset_done'},
        name="password_reset"),
   url(r'^reset/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'),
   url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete', name='password_reset_complete'),
]




Django templates for registration

We want to copy Django's template files for password reset to our templates. First, we need to find where our Django has been installed.

$ python
Python 2.7.5 (default, Jun 24 2015, 00:41:19)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django

Let's go to /usr/lib64/python2.7/site-packages/django/contrib/admin/templates/registration/:

$ pwd
/usr/lib64/python2.7/site-packages/django/contrib/admin/templates/registration

$ ls
logged_out.html            password_reset_complete.html  password_reset_email.html
password_change_done.html  password_reset_confirm.html   password_reset_form.html
password_change_form.html  password_reset_done.html

Now we can copy the registration folder to templates root directory:

$ pwd
/srv/www/django/djangotest/driver/templates

$ cp -r /usr/lib64/python2.7/site-packages/django/contrib/admin/templates/registration .

Now we have registration folder under driver/templates

$ ls
login.html  register.html  registration

$ cd registration

$ ls
logged_out.html            password_reset_complete.html  password_reset_email.html
password_change_done.html  password_reset_confirm.html   password_reset_form.html
password_change_form.html  password_reset_done.html

$ rm logged_out.html

$ ls
password_change_done.html     password_reset_confirm.html  password_reset_form.html
password_change_form.html     password_reset_done.html
password_reset_complete.html  password_reset_email.html


tree-templates-root2.png



Reset on Login page


user-reg.png

ResetItLink.png



password_reset_form.html
{% extends "base.html" %}
{% load i18n %}

{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
› {% trans 'Password reset' %}
</div>
{% endblock %}

{% block title %}{{ title }}{% endblock %}
{% block content_title %}<h1>{{ title }}</h1>{% endblock %}
{% block content %}

<p>{% trans "Forgotten your password?? Enter your email address below, and we'll email instructions for setting a new one." %}</p>

<form action="" method="post">{% csrf_token %}
{{ form.email.errors }}
<p><label for="id_email">{% trans 'Email address:' %}</label> {{ form.email }} <input type="submit" value="{% trans 'Reset my password' %}" /></p>
</form>

{% endblock %}

Django's template finders let us override any template. Though we placed the admin templates under driver we want to override, the order matters. So, it should look like this:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'car',
    'tinymce',
    'pages',
    'driver',
    'django.contrib.admin',
)  

Click the "Reset it!" link on Login page, and type in our email:


resset-password.png



smtp - email

When we click "Reset my password" with an email, we may got the following "Connection refused" error:

ConnectionRefusedError.png

We need to add the following lines in settings.py to setup mail host:

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'kihyuck.hong@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

Once the settings.py is modified, we can click "Reset my password" button. Then, the email will be sent from the EMAIL_HOST with EMAIL_HOST_USER as a sender:

PasswordResetSent.png

We can see the email in our Inbox:

cbogotobogo-email-got.png

If we click the link of the email received, we get a page for the New email password setting:

NewPassword.png

Click "Change my password":

SuccessfulPasswordReset.png



Files

Here is the files we've created so far:

tree2.png
tree3.png












Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Django 1.8



Introduction - Install Django and Project Setup

Creating and Activating Models

Hello World A - urls & views

Hello World B - templates

Hello World C - url dispatcher

Hello World D - Models and SQLite Database

MVC - Hello World

Hello World on a Shared Host A

Hello World on a Shared Host B

Hello World - Admin Site Setup

virtualenv

Creating test project on virtualenv

Test project's settings.py

Creating Blog app and setting up models

Blog app - syncdb A

Blog app - syncdb B

Blog app - views and urls

Blog app - templates

Blog app - class based templates

Image upload sample code - local host

Authentication on Shared Host using FastCGI

User Registration on Shared Host A

User Registration with a Customized Form on Shared Host B

Blogs on Shared Host

Serving Django app with uWSGI and Nginx

Image upload sample code - shared host

Managing (Deploying) Static files (CSS, Images, Javascript) on Shared Host

Forum application on a Shared Host

Django Python Social Auth : Getting App ID (OAuth2) - Facebook, Twitter, and Google

Django: Python social auth, Facebook, Twitter, and Google Auth

Django: Python social auth, Facebook, Twitter, and Google Auth with Static files

...

Django 1.8 hosted on Linode VPS ==>

1. Setup CentOS 7 hosted on VPS

1B. Setup CentOS 7 hosted on VPS (multi-domain hosting setup) - Name server and Zone File settings (from GoDaddy to Linode)

2. ssh login and firewall

3. Apache Install

4. Install and Configure MariaDB Database server & PHP

5. Install and Configure Django

6. Model

7. Model 2 : populate tables, list_display, and search_fields

8. Model 3 (using shell)

9. Views (templates and css)

10. Views 2 (home page and more templates)

11. TinyMCE

12. TinyMCE 2

13. ImageField/FileField : Serving image/video files uploaded by a user

14. User Authentication 1 (register & forms)

15. User Authentication 2 (login / logout)

16. User Authentication 3 (password reset) - Sent from Email (gmail) setup etc.

17. User Authentication 4 (User profile & @login_required decorator)

18. User Authentication 5 (Facebook login)

19. User Authentication 6 (Google login)

20. User Authentication 7 (Twitter login)

21. User Authentication 8 (Facebook/Google/Twitter login buttons)

22. Facebook open graph API timeline fan page custom tab 1

23. Facebook Open Graph API Timeline Fan Page Custom Tab 2 (SSL certificate setup)

24. Facebook open graph API timeline fan page custom tab 3 (Django side - urls.py, settings.py, and views.py)

...

A sample production site Django 1.8.7: sfvue.com / einsteinish.com ==>

A sample production app (sfvue.com) with virtualenv and Apache

2. Upgrading to Django 1.8.7 sfvue.com site sample with virtualenv and Apache

(*) Django 1.8.7 einsteinish.com site - errors and fixes

Django 1.8.12 pytune.com site - local with Apache mod_wsgi

Django 1.8.12 pytune.com site - local with Nginx and uWSGI

Django 1.8.12 pytune.com site - deploy to AWS with Nginx and uWSGI

Django Haystack with Elasticsearch and Postgres

Django Compatibility Cheat Sheet

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master