Updating 1.10 to 1.11.1 and AttributeError

137 views
Skip to first unread message

Jorge Cadena

unread,
May 22, 2017, 6:40:11 PM5/22/17
to Django users
Hello.

updating 1.10 to 1.11.1 and get this error:

  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/channels/management/commands/runserver.py", line 38, in inner_run
    return RunserverCommand.inner_run(self, *args, **options)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/utils/functional.
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/urls/resolvers.py
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/utils/functional.
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/urls/resolvers.py
    return import_module(self.urlconf_name)
  File "/home/aztrock/workspace/ariatel.com.co/lib/python3.5/importlib/__init__.py", line 126, in import_
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 673, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/aztrock/workspace/ariatel.com.co/kibox/billing/urls.py", line 9, in <module>
    from app.usuarios import views as UserViews
  File "/home/aztrock/workspace/ariatel.com.co/kibox/app/usuarios/views.py", line 31, in <module>
    from .form import (
  File "/home/aztrock/workspace/ariatel.com.co/kibox/app/usuarios/form.py", line 22, in <module>
    class UsuarioNuevoForm(forms.ModelForm):
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/forms/models.py",
    opts.field_classes)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/forms/models.py",
    formfield = f.formfield(**kwargs)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/db/models/fields/
    'queryset': self.remote_field.model._default_manager.using(db),
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/db/models/manager
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/db/models/query.p
    clone = self._clone()
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/db/models/query.p
    query = self.query.clone()
  File "/home/aztrock/workspace/ariatel.com.co/local/lib/python3.5/site-packages/django/db/models/sql/que
    obj.select_for_update_skip_locked = self.select_for_update_skip_locked
AttributeError: 'Query' object has no attribute 'select_for_update_skip_locked'

models

class Usuarios(AbstractBaseUser, PermissionsMixin):
    codigo_cliente = models.BigIntegerField(
        null=True,
        blank=True,
    )
    first_name = models.CharField(_('Nombres'),
                                  max_length=30,
                                  help_text="Nombres")
    last_name = models.CharField(
        _('Apellidos'),
        max_length=30,
        help_text="Apellidos",
        blank=True,
        null=True
    )
    email = models.EmailField(
        verbose_name='correo electronico',
        max_length=255,
        # unique=True,
        db_index=True,
        help_text=_(
            """
            Correo electronico valido, para notificaciones,
            recuperacion de contraseñas, promociones, avisos
            """
        )
    )
....


forms.py

class UsuarioNuevoForm(forms.ModelForm):

    password = forms.CharField(widget=forms.PasswordInput(render_value=False))
    password1 = forms.CharField(widget=forms.PasswordInput(render_value=False))
    observaciones = forms.CharField(
        widget=forms.Textarea(attrs={'cols': 80, 'rows': 3}), required=False
    )

    class Media:

        css = {
            "all": ("css/inputTags.min.css", )
        }
        js = (
            'js/plugins/input_tags/InputTags.min.js',
        )

    class Meta:
        model = Usuarios
        # fields = ('username', 'email', 'password', 'password1', 'plan', 'observaciones')
        exclude = (
            'codigo_unico', 'last_login', 'sub_usuario_grupo', "plan_sms", 'site', "last_name", "codigo_cliente", "site", "fas"
        )

    def __init__(self, *args, **kwargs):
        # user = kwargs.pop('user', None)
        super(UsuarioNuevoForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update({'autofocus': 'autofocus'})

        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.label_class = 'col-md-2'
        self.helper.field_class = 'col-md-10'
        self.helper.layout = Layout(
            Div(
                Div(
                    Div(
                        Div(
                            Fieldset(
                                "Personal",
                                "username",
                                "password", "password1",
                                "first_name", "email",
                                Field(
                                    "routing_rol",
                                    css_class="chosen-select",
                                    style="width: 240px;",
                                    tabindex="3",
                                ),
                                Field(
                                    "pais",
                                    css_class="chosen-select",
                                    style="width: 240px;",
                                    tabindex="3",
                                ), "ciudad", "direccion", "movil", "fijo", "nit_cc"
                            )
                        ),
                        css_class="col-md-6"
                    ),
                    Div(
                        Fieldset(
                            "Avanzado",
                            "limite_llamadas", "cod_respuesta",
                            Field(
                                "tipo_de_visor",
                                css_class="chosen-select",
                                style="width: 240px;",
                                tabindex="3",
                            ),
                            Field(
                                "metodo_facturacion",
                                css_class="chosen-select",
                                style="width: 240px;",
                                tabindex="3",
                            ),
                            Field(
                                "rol_group",
                                css_class="chosen-select",
                                style="width: 240px;",
                                tabindex="3",
                            ),
                            Div(
                                Field("duration_failed_lo"),
                                Field("duration_failed"),
                            ),
                            "credito_limite",
                            "facturacion_tiempo",
                            "facturacion_tarificador",
                            "base_notificacion",
                            "porcentaje_reventa",
                            "only_one_call"
                        ),
                        css_class="col-md-6"
                    ),
                ),
                Div(
                    Div(
                        Div(
                            Fieldset(
                                "Notificaciones y facturacion",
                                Field(
                                    "ciclo_facturacion",
                                    css_class="chosen-select",
                                    style="width: 240px;",
                                    tabindex="3",
                                ), "adjuntar_cdr_email"
                            )
                        ),
                        css_class="col-md-6"
                    ),
                    Div(
                        Div(
                            Fieldset(
                                "Numeros para Tarjetas de Llamadas",
                                Field(
                                    "play_audio",
                                    css_class="onoffswitch-checkbox",
                                    template='crispy_template/checkbox_switch.html',
                                ),
                                Field(
                                    "ringback",
                                    css_class="onoffswitch-checkbox",
                                    template='crispy_template/checkbox_switch.html',
                                ),
                                Field(
                                    "ringback_set",
                                ),
                                Field(
                                    "numeros",
                                    css_class="inputTags-field"
                                )
                            )
                        ),
                        css_class="col-md-6"
                    ),
                    css_class="col-md-12"
                ),
                HTML("""
                    <script>
                        $('#id_numeros').inputTags({
                            change: function($elem) {
                                console.log('Event called on tag selection', $elem);
                            }
                        });
                    </script>
                """),
                css_class="row"
            )
        )

        # if user.es_reseller:
        #     del self.fields['cod_respuesta']
        #     del self.fields['enrutamiento_unico']
        #     # del self.helper.layout[0][9]
        #     # del self.helper.layout[0][10]
        #     # del self.helper.layout[0][3]
        #     pass

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            User.objects.get(email=email)
        except Exception:
            return email.lower()
        raise forms.ValidationError("Email ya se encuentra registrado")

    def clean_username(self):
        username = self.cleaned_data['username']

        # Nobre de usuario muy corto
        if len(username) <= 5:
            raise forms.ValidationError("Nombre de usuario demasiado Corto")

        # Nombre de usuario con espacios.
        if re.search('\W', username):
            raise forms.ValidationError("Nombre de usuario no debe contener ningun caracter especial.")

        # Nombre de usuario ya existe.
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username

        raise forms.ValidationError("Nombre de usuario ya se encuentra registrado, Seleccionar otro")

    def clean_password(self):
        if not self.cleaned_data['password']:
            raise forms.ValidationError("Este campo es requerido")
        return self.cleaned_data['password']

    def clean(self):
        try:
            password = self.cleaned_data['password']
        except Exception:
            raise forms.ValidationError("Este campo es requerido")
        try:
            password1 = self.cleaned_data['password1']
        except Exception:
            raise forms.ValidationError("Este campo es requerido")

        if password != password1:
            raise forms.ValidationError("Password no son iguales, intentar de nuevo" + self.cleaned_data['password'])
        return self.cleaned_data
 

and documentation django:

https://docs.djangoproject.com/en/1.11/releases/1.11/#database-backends
https://docs.djangoproject.com/en/1.11/releases/1.11/#database-backend-api

i'm not sure where config this options.

Thanks

Tim Graham

unread,
May 22, 2017, 10:29:25 PM5/22/17
to Django users
Which database backend are you using? I wonder if it's a third-party backend that hasn't been updated for Django 1.11.

Jorge Cadena

unread,
May 23, 2017, 8:52:56 AM5/23/17
to Django users
Hi

using: django.db.backends.postgresql_psycopg2

DATABASE_ROUTERS = ['app.general.router.DatabaseAppsRouter']


router.py
"""Router control all database operations on models for different dababases.

.. versionadded:: 3.0

"""
from django.conf import settings


class DatabaseAppsRouter(object):
    """A router to control all database operations on models for different databases.

    In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
    will fallback to the `default` database.

    Example:
        DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
    """

    def db_for_read(self, model, **hints):
        """"Point all read operations to the specific database."""
        if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
            return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
        return None

    def db_for_write(self, model, **hints):
        """Point all write operations to the specific database."""
        if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
            return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """Allow any relation between apps that use the same database."""
        db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label)
        db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label)
        if db_obj1 and db_obj2:
            if db_obj1 == db_obj2:
                return True
            else:
                return False
        return None

    def allow_syncdb(self, db, model):
        """Make sure that apps only appear in the related database."""
        if db in settings.DATABASE_APPS_MAPPING.values():
            return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db
        elif model._meta.app_label in settings.DATABASE_APPS_MAPPING:
            return False
        return None

Simon Charette

unread,
May 23, 2017, 9:34:27 AM5/23/17
to Django users
Hello,

Could you please share all of your INSTALLED_APPS?

Are you using any kind of query caching?

Thanks,
Simon

Jorge Cadena

unread,
May 24, 2017, 1:30:34 PM5/24/17
to Django users
My apps


INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.humanize',
    'app.usuarios',
    'app.general',
    'app.routing',
    'app.sip',
    'app.destinos',
    'app.medios_de_pagos',
    'app.admin_ip',
    'app.reportes',
    'app.notificaciones',
    'app.recarga',
    'app.pbx',
    'app.calling_card',
    'app.campaigns',
    'app.click_to_call',
    'app.at',
    'app.operator_portability',
    'app.apprest',
    # Plugins ##
    'notifications',
    'formtools',
    'tinymce',
    'crispy_forms',
    'two_factor',
    'redisboard',
    'django_tables2',
    'django_otp',
    'django_otp.plugins.otp_static',
    'django_otp.plugins.otp_totp',
    'debug_toolbar.apps.DebugToolbarConfig',
    'django_countries',
    'django_celery_beat',
    'django_extensions',

    'channels',
    'channels.delay'
)

query caching not, only cache normal

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'



El lunes, 22 de mayo de 2017, 17:40:11 (UTC-5), Jorge Cadena escribió:

birkin

unread,
May 26, 2017, 10:04:36 AM5/26/17
to Django users
Simon, thanks. I was getting the same error.

I was caching the query, and thought I'd turned it off, but was still getting the error.

Running my webapp via runserver (instead of my usual approach of using passenger) showed the problem:

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
/path/to/env/lib/python3.6/site-packages/django/core/cache/backends/filebased.py:41: RuntimeWarning: Pickled model instance's Django version 1.10.6 does not match the current version 1.11.1.
  return pickle.loads(zlib.decompress(f.read()))

Once I cleared the cached files on the disk, the problem went away. Hope this helps, Jorge!

-Birkin
Reply all
Reply to author
Forward
0 new messages