#30549: Error while saving the user.
-------------------------------------+-------------------------------------
               Reporter:  Shritesh   |          Owner:  (none)
  Jamulkar                           |
                   Type:  Bug        |         Status:  new
              Component:  Error      |        Version:  2.2
  reporting                          |
               Severity:  Normal     |       Keywords:  password validation
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 Hello, community,
    I was creating a new user by the custom form with a custom author model
 inheriting default user model. I encountered this error while I was saving
 the user in database.

 Here are my all relevant files.

 **blograms/settings.py**
 {{{
 """
 Django settings for blograms project.

 Generated by 'django-admin startproject' using Django 2.2.1.

 For more information on this file, see
 https://docs.djangoproject.com/en/2.2/topics/settings/

 For the full list of settings and their values, see
 https://docs.djangoproject.com/en/2.2/ref/settings/
 """

 import os
 from decouple import config

 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


 # Quick-start development settings - unsuitable for production
 # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

 # SECURITY WARNING: keep the secret key used in production secret!
 SECRET_KEY = config('SECRET_KEY')

 # SECURITY WARNING: don't run with debug turned on in production!
 DEBUG = True

 ALLOWED_HOSTS = []


 # Application definition

 INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'phonenumber_field',
     'widget_tweaks',
     'blog.apps.BlogConfig',
     'user.apps.UserConfig'
 ]

 MIDDLEWARE = [
     'django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ]

 ROOT_URLCONF = 'blograms.urls'

 TEMPLATES = [
     {
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
         'DIRS': [os.path.join(BASE_DIR, 'templates')]
         ,
         'APP_DIRS': True,
         'OPTIONS': {
             'context_processors': [
                 'django.template.context_processors.debug',
                 'django.template.context_processors.request',
                 'django.contrib.auth.context_processors.auth',
                 'django.contrib.messages.context_processors.messages',
             ],
         },
     },
 ]

 WSGI_APPLICATION = 'blograms.wsgi.application'


 # Database
 # https://docs.djangoproject.com/en/2.2/ref/settings/#databases

 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
     }
 }


 # Password validation
 # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-
 validators

 AUTH_PASSWORD_VALIDATORS = [
     {
         'NAME':
 
'django.contrib.registration.password_validation.UserAttributeSimilarityValidator',
     },
     {
         'NAME':
 'django.contrib.registration.password_validation.MinimumLengthValidator',
     },
     {
         'NAME':
 'django.contrib.registration.password_validation.CommonPasswordValidator',
     },
     {
         'NAME':
 'django.contrib.registration.password_validation.NumericPasswordValidator',
     },
 ]


 # Internationalization
 # https://docs.djangoproject.com/en/2.2/topics/i18n/

 LANGUAGE_CODE = 'en-us'

 TIME_ZONE = 'UTC'

 USE_I18N = True

 USE_L10N = True

 USE_TZ = True


 # Static files (CSS, JavaScript, Images)
 # https://docs.djangoproject.com/en/2.2/howto/static-files/

 STATIC_URL = '/static/'
 STATICFILES_DIRS = [
     os.path.join(BASE_DIR, "static")
 ]

 LOGIN_REDIRECT_URL = '/'
 LOGOUT_REDIRECT_URL = '/'
 }}}

 **blograms/urls.py**
 {{{
 """blograms URL Configuration

 The `urlpatterns` list routes URLs to views. For more information please
 see:
     https://docs.djangoproject.com/en/2.2/topics/http/urls/
 Examples:
 Function views
     1. Add an import:  from my_app import views
     2. Add a URL to urlpatterns:  path('', views.home, name='home')
 Class-based views
     1. Add an import:  from other_app.views import Home
     2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
 Including another URLconf
     1. Import the include() function: from django.urls import include,
 path
     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
 """
 from django.conf.urls.static import static
 from django.contrib import admin
 from django.urls import path, include

 from blograms import settings

 urlpatterns = [
     path('admin/', admin.site.urls),
     path('', include('blog.urls')),
     path('user/', include('user.urls'))
 ] + static(settings.STATIC_URL,
 document_root=settings.STATICFILES_DIRS[0])

 }}}

 **user/views.py**

 {{{
 from django.shortcuts import render, redirect, HttpResponse,
 HttpResponseRedirect
 from django.contrib.auth import login, logout, authenticate
 from .forms import *
 from django.contrib.auth.models import User
 from django.http import Http404
 from django.contrib.auth.forms import AuthenticationForm
 import json


 # Create your views here.

 def webNew(request):
     if request.user.is_authenticated:
         return HttpResponseRedirect('/')
     if request.method == 'POST':
         user_form = UserForm(request.POST)
         author_form = AuthorForm(request.POST)
         result = {
             'error': []
         }

         if user_form.is_valid() and author_form.is_valid():
                 user = user_form.save()
                 user.set_password(user.password)
                 user.save()

                 author = author_form.save(commit=False)
                 author.author = user

                 author.save()
 authenticate(request,username=user.username,password=user.password)
                 login(request, user)
                 result['success'] = True
         else:
                 result['success'] = False
                 for k,v in user_form.errors.items():
                     result['error'].extend(v)
                 for k,v in author_form.errors.items():
                     result['error'].extend(v)

         # except Exception as e:
         #     result['success'] = False
         #     if hasattr(e, 'message'):
         #         result['error'] = e.message
         #     else:
         #         result['error'] = ['Something went Wrong']
         return HttpResponse(json.dumps(result),
 content_type="application/json")


 def webProfile(request, username=''):
     if username is not '':
         try:
             user = User.objects.get(username=username)
             # TODO: Follower logic
             return render(request, 'user/profile.html', {'vuser': user})
         except Exception as e:
             return Http404
     return redirect('/')


 def webLogin(request):
     if request.user.is_authenticated:
         return HttpResponseRedirect('/')
     if request.method == 'POST':
         form = AuthenticationForm(request, request.POST)
         result = {
             'error': []
         }
         if form.is_valid():
             try:
                 login(request, form.get_user())
                 result['success'] = True
                 result['error'] = 'None'
             except Exception as e:
                 result['success'] = False
                 if hasattr(e, 'message'):
                     result['error'] = e.message
                 else:
                     result['error'] = ['Something went Wrong']
         else:
             result['success'] = False
         for k, v in form.errors.items():
             result['error'].extend(v)
         print(result)
         return HttpResponse(json.dumps(result),
 content_type="application/json")


 def webLogout(request):
     logout(request)
     return redirect('/')
 }}}

 **forms.py**
 {{{
 from django import forms
 from django.contrib.auth.models import User
 from .models import Author


 class UserForm(forms.ModelForm):
     password = forms.CharField(widget=forms.PasswordInput())

     class Meta():
         model = User
         fields = ('email', 'username', 'password')


 class AuthorForm(forms.ModelForm):

     class Meta():
         model = Author
         fields = ['phone']

 }}}

 **user/urls.py**
 {{{
 from django.conf.urls.static import static
 from django.urls import path,include

 from blograms import settings
 from . import views

 urlpatterns = [
    path('login/', views.webLogin, name='web_login'),
    path('logout/', views.webLogout, name='web_logout'),
    path('new/', views.webNew, name='web_login'),
    path('<str:username>/', views.webProfile, name="web_profile"),

 ] + static(settings.STATIC_URL,
 document_root=settings.STATICFILES_DIRS[0])
 }}}

 **blog/views.py**
 {{{
 from django.shortcuts import render
 from  django.contrib.auth.forms import AuthenticationForm
 from user.forms import *
 from django.contrib.auth.models import User
 # Create your views here.
 def home(request):
     context = {
         'form': AuthenticationForm,
         'form1': UserForm(),
         'form2': AuthorForm()
     }
     if request.user.username is not '':
         user = User.objects.get(username=request.user.username)
         context['user'] = user
     return render(request, 'blog/index.html',context)
 }}}

 **templates/user/auth.html**
 {{{
 {% load widget_tweaks %}
 <div class="modal login-modal">
     <div class="modal-background"></div>
     <div class="modal-card">
         <header class="modal-card-head">
             <p class="modal-card-title">Let's Get Started</p>
             <button class="close-modal delete" aria-
 label="close"></button>
         </header>
         <section class="modal-card-body">
             <div class="container notification is-hidden is-danger
 error"></div>
             <div class="cloumns is-inline-flex-desktop">
                 <div class="column is-half">
                     <form id="login-form" method="post">
                         {% csrf_token %}
                         <label class="label is-large">Login</label>
                         <div class="field">
                             <p class="control has-icons-left has-icons-
 right">
                                 {% render_field form.username
 class+="input login-username" placeholder+="Username" %}
                                 <span class="icon is-small is-left">
       <i class="fas fa-user"></i>
     </span>
                             </p>
                         </div>
                         <div class="field">
                             <p class="control has-icons-left">
                                 {% render_field form.password
 class+="input login-password" placeholder+="Password" %}
                                 <span class="icon is-small is-left">
       <i class="fas fa-lock"></i>
     </span>
                             </p>
                         </div>
                         <button class="button is-success"
 type="submit">Login</button>
                     </form>
                 </div>
                 <div class="container column is-hidden-desktop has-text-
 centered is-size-5">OR</div>
                 <div class="column is-half">
                     <form id="signup-form" enctype="multipart/form-data"
 method="post">
                         <label class="label is-large">Sign Up</label>
                         {% csrf_token %}
                         <div class="field">
                             <p class="control has-icons-left has-icons-
 right">
                                 {% render_field form1.username
 class+="input signup-username" id+="signup-username"
 placeholder+="Username" %}
                                 <span class="icon is-small is-left">
       <i class="fas fa-user"></i>
     </span>
                             </p>
                         </div>
                         <div class="field">
                             <p class="control has-icons-left has-icons-
 right">
                                 {% render_field form1.email class+="input
 signup-email" placeholder+="Email" %}
                                 <span class="icon is-small is-left">
       <i class="fas fa-envelope"></i>
     </span>
                             </p>
                         </div>
                         <div class="field">
                             <p class="control has-icons-left">
                                 {% render_field form1.password
 class+="input signup-password" id+="signup-password"
 placeholder+="Password" %}
                                 <span class="icon is-small is-left">
       <i class="fas fa-lock"></i>
     </span>
                             </p>
                         </div>
                         <div class="field">
                             <p class="control has-icons-left has-icons-
 right">
                                 {% render_field form2.phone class+="input
 signup-phone" placeholder+="Phone" %}
                                 <span class="icon is-small is-left">
       <i class="fas fa-phone"></i>
     </span>
                             </p>
                         </div>
                         <button class="button is-success"
 type="submit">Sign Up</button>
                     </form>
                 </div>
             </div>
         </section>
         <footer class="modal-card-foot">
         </footer>
     </div>
 </div>
 }}}

 **Error Traceback**
 {{{
 Internal Server Error: /user/new/
 Traceback (most recent call last):
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/contrib/auth/password_validation.py", line 26, in
 get_password_validators
     klass = import_string(validator['NAME'])
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/utils/module_loading.py", line 17, in import_string
     module = import_module(module_path)
   File
 "/home/shritesh99/anaconda3/envs/all/lib/python3.6/importlib/__init__.py",
 line 126, in import_module
     return _bootstrap._gcd_import(name[level:], package, level)
   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
   File "<frozen importlib._bootstrap>", line 941, in
 _find_and_load_unlocked
   File "<frozen importlib._bootstrap>", line 219, in
 _call_with_frames_removed
   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
   File "<frozen importlib._bootstrap>", line 953, in
 _find_and_load_unlocked
 ModuleNotFoundError: No module named 'django.contrib.registration'

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/core/handlers/exception.py", line 34, in inner
     response = get_response(request)
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/core/handlers/base.py", line 115, in _get_response
     response = self.process_exception_by_middleware(e, request)
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/core/handlers/base.py", line 113, in _get_response
     response = wrapped_callback(request, *callback_args,
 **callback_kwargs)
   File "/home/shritesh99/PycharmProjects/blograms/user/views.py", line 25,
 in webNew
     user.save()
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/contrib/auth/base_user.py", line 68, in save
     password_validation.password_changed(self._password, self)
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/contrib/auth/password_validation.py", line 60, in
 password_changed
     password_validators = get_default_password_validators()
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/contrib/auth/password_validation.py", line 19, in
 get_default_password_validators
     return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)
   File "/home/shritesh99/anaconda3/envs/all/lib/python3.6/site-
 packages/django/contrib/auth/password_validation.py", line 29, in
 get_password_validators
     raise ImproperlyConfigured(msg % validator['NAME'])
 django.core.exceptions.ImproperlyConfigured: The module in NAME could not
 be imported:
 
django.contrib.registration.password_validation.UserAttributeSimilarityValidator.
 Check your AUTH_PASSWORD_VALIDATORS setting.
 [06/Jun/2019 14:38:57] "POST /user/new/ HTTP/1.1" 500 17511
 }}}

 Thankyou in advance.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/30549>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/053.68774702c192cbf03bd0cb2e912dd70f%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to