Wednesday, July 1, 2015

User registration form with CAPTCHA using django-simple-captcha using python

sample web registration in python




  1. import web

  2. # Init our application, this is just about the most basic setup
  3. render = web.template.render('/var/www/templates/')
  4. urls = ('/', 'Index')
  5. app = web.application(urls, globals())

  6. class Index:
  7.     # Create a basic form shared by the class methods
  8.     def __init__(self):
  9.        self.registerForm = web.form.Form(
  10.             # We're adding some fields and a submit button
  11.             # Each field has a validator, which verifies its correctness
  12.             # In this case we check if the field is not null
  13.             # Other attributes are available: description, id, HTML class name, etc
  14.             # See http://webpy.org/form for reference
  15.             web.form.Textbox('username', web.form.notnull, description='User name'),
  16.             web.form.Password('password', web.form.notnull, description='Password'),
  17.             web.form.Password('repeat_password', web.form.notnull,
  18.                               description='Repeat password'),
  19.             web.form.Button('Register'),

  20.             # Whole forms can have validators, too
  21.             # Here, we check if password fields have the same content
  22.             validators = [web.form.Validator("Passwords didn't match.", lambda i:
  23.                                              i.password == i.repeat_password)]
  24.         )

  25.     # GET method is used when there is no form data sent to the server
  26.     def GET(self):
  27.         form = self.registerForm()
  28.         return render.form(content=form)

  29.     # POST method carries form data
  30.     def POST(self):
  31.         # Notice how flawlessly web.py form works, receiving all the data for us
  32.         form = self.registerForm()

  33.         if(not form.validates()):
  34.             return render.form(content=form)
  35.         else:
  36.             return "Form successfuly sent! Username: %s, password: %s" % \
  37.                 (form.d.username, form.d.password)

  38. application = app.wsgifunc()

  39. if __name__=="__main__":
  40.     app.run()




  41. user.py


  42. # Django settings for app project.

  43. # Import the os.path module for doing manipulation with file paths.
  44. import os.path

  45. DEBUG = True
  46. TEMPLATE_DEBUG = DEBUG

  47. ADMINS = (
  48.     # ('Your Name', 'your_email@example.com'),
  49. )

  50. MANAGERS = ADMINS

  51. DATABASES = {
  52.     'default': {
  53.         'ENGINE': 'django.db.backends.sqlite3', # # Using sqlite3
  54.         'NAME': '/var/www/mydb', # Absolute path to the database file
  55.         # The following settings are not used with sqlite3:
  56.         'USER': '',
  57.         'PASSWORD': '',
  58.         'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
  59.         'PORT': '',                      # Set to empty string for default.
  60.     }
  61. }

  62. # Hosts/domain names that are valid for this site; required if DEBUG is False
  63. # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
  64. ALLOWED_HOSTS = []

  65. # Local time zone for this installation. Choices can be found here:
  66. # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
  67. # although not all choices may be available on all operating systems.
  68. # In a Windows environment this must be set to your system time zone.
  69. TIME_ZONE = 'America/Los_Angeles'

  70. # Language code for this installation. All choices can be found here:
  71. # http://www.i18nguy.com/unicode/language-identifiers.html
  72. LANGUAGE_CODE = 'en-us'

  73. SITE_ID = 1

  74. # If you set this to False, Django will make some optimizations so as not
  75. # to load the internationalization machinery.
  76. USE_I18N = True

  77. # If you set this to False, Django will not format dates, numbers and
  78. # calendars according to the current locale.
  79. USE_L10N = True

  80. # If you set this to False, Django will not use timezone-aware datetimes.
  81. USE_TZ = True

  82. # Absolute filesystem path to the directory that will hold user-uploaded files.
  83. # Example: "/var/www/example.com/media/"
  84. MEDIA_ROOT = ''

  85. # URL that handles the media served from MEDIA_ROOT. Make sure to use a
  86. # trailing slash.
  87. # Examples: "http://example.com/media/", "http://media.example.com/"
  88. MEDIA_URL = ''

  89. # Absolute path to the directory static files should be collected to.
  90. # Don't put anything in this directory yourself; store your static files
  91. # in apps' "static/" subdirectories and in STATICFILES_DIRS.
  92. # Example: "/var/www/example.com/static/"
  93. STATIC_ROOT = '/var/www/app/static/'

  94. # URL prefix for static files.
  95. # Example: "http://example.com/static/", "http://static.example.com/"
  96. STATIC_URL = '/static/'

  97. # Additional locations of static files
  98. STATICFILES_DIRS = (
  99.     # Put strings here, like "/home/html/static" or "C:/www/django/static".
  100.     # Always use forward slashes, even on Windows.
  101.     # Don't forget to use absolute paths, not relative paths.
  102. )

  103. # List of finder classes that know how to find static files in
  104. # various locations.
  105. STATICFILES_FINDERS = (
  106.     'django.contrib.staticfiles.finders.FileSystemFinder',
  107.     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
  108. #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
  109. )

  110. # Make this unique, and don't share it with anybody.
  111. SECRET_KEY = 'vw7__ve*_3j^edw+@9k9(24_efqjnul-k=84yis*ew$xstr&*!'

  112. # List of callables that know how to import templates from various sources.
  113. TEMPLATE_LOADERS = (
  114.     'django.template.loaders.filesystem.Loader',
  115.     'django.template.loaders.app_directories.Loader',
  116. #     'django.template.loaders.eggs.Loader',
  117. )

  118. MIDDLEWARE_CLASSES = (
  119.     'django.middleware.common.CommonMiddleware',
  120.     'django.contrib.sessions.middleware.SessionMiddleware',
  121.     'django.middleware.csrf.CsrfViewMiddleware',
  122.     'django.contrib.auth.middleware.AuthenticationMiddleware',
  123.     'django.contrib.messages.middleware.MessageMiddleware',
  124.     # Uncomment the next line for simple clickjacking protection:
  125.     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  126. )

  127. ROOT_URLCONF = 'app.urls'

  128. # Python dotted path to the WSGI application used by Django's runserver.
  129. WSGI_APPLICATION = 'app.wsgi.application'

  130. TEMPLATE_DIRS = (
  131.     # Include the "templates" directory in the current directory.
  132.     os.path.join(os.path.dirname(__file__), "templates"),
  133.     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
  134.     # Always use forward slashes, even on Windows.
  135.     # Don't forget to use absolute paths, not relative paths.
  136. )

  137. INSTALLED_APPS = (
  138.     'django.contrib.auth',
  139.     'django.contrib.contenttypes',
  140.     'django.contrib.sessions',
  141.     'django.contrib.sites',
  142.     'django.contrib.messages',
  143.     'django.contrib.staticfiles',
  144.     'captcha', # Include the django-simple-captcha application
  145.     'registration', # Include the registration
  146.     # Uncomment the next line to enable the admin:
  147.     # 'django.contrib.admin',
  148.     # Uncomment the next line to enable admin documentation:
  149.     # 'django.contrib.admindocs',
  150. )

  151. # A sample logging configuration. The only tangible logging
  152. # performed by this configuration is to send an email to
  153. # the site admins on every HTTP 500 error when DEBUG=False.
  154. # See http://docs.djangoproject.com/en/dev/topics/logging for
  155. # more details on how to customize your logging configuration.
  156. LOGGING = {
  157.     'version': 1,
  158.     'disable_existing_loggers': False,
  159.     'filters': {
  160.         'require_debug_false': {
  161.             '()': 'django.utils.log.RequireDebugFalse'
  162.         }
  163.     },
  164.     'handlers': {
  165.         'mail_admins': {
  166.             'level': 'ERROR',
  167.             'filters': ['require_debug_false'],
  168.             'class': 'django.utils.log.AdminEmailHandler'
  169.         }
  170.     },
  171.     'loggers': {
  172.         'django.request': {
  173.             'handlers': ['mail_admins'],
  174.             'level': 'ERROR',
  175.             'propagate': True,
  176.         },
  177.     }

  178. }

4 comments:

  1. The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept.
    python Training institute in Pune
    python Training institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  2. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Best Devops online Training
    Online DevOps Certification Course - Gangboard
    Best Devops Training institute in Chennai

    ReplyDelete
  3. Very nice article, I enjoyed reading your post, very nice share, I want to twit this to my followers. Thanks!. python classes in pune

    ReplyDelete