User Tools

Site Tools


informatica:linux:django

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
informatica:linux:django [2014/03/11 12:32] javiinformatica:linux:django [2019/05/19 16:55] (current) – [Activar la interfaz administrativa en app1 y tabla 'Tabla1'] javi
Line 2: Line 2:
  
 django python framework django python framework
 +
 +===== Instalacion =====
 +
 +1. Instalar pip
 +
 +  sudo aptitude update; sudo aptitude install python-pip
 +  
 +2. Instalar ultima version de django:
 +
 +  sudo pip install Django==1.8
  
 ===== Primeros pasos ===== ===== Primeros pasos =====
Line 91: Line 101:
   python manage.py runserver 0.0.0.0:8080   python manage.py runserver 0.0.0.0:8080
  
-===== Activar la interfaz administrativa =====+===== Interfaz administrativa ===== 
 + 
 +Ahora la interfaz administrativa se activa por defecto 
 + 
 +==== Crear superusuario ==== 
 + 
 +https://docs.djangoproject.com/en/2.2/ref/django-admin/#django-admin-createsuperuser 
 + 
 +==== (Deprecated) Activar la interfaz administrativa =====
  
 1 1
Line 117: Line 135:
  
  
-====Activar la interfaz administrativa en app1 y tabla 'Tabla1' =====+==== (Deprecated) Activar la interfaz administrativa en app1 y tabla 'Tabla1' ====
  
 2.1 Crear: 2.1 Crear:
Line 332: Line 350:
   Tabla1.objects.filter(pub_date__year=2006)   Tabla1.objects.filter(pub_date__year=2006)
      
-===== Instalacion manual ===== 
- 
-1. Download the latest release from our download page. 
- 
-2. Untar the downloaded file (e.g. tar xzvf Django-X.Y.tar.gz, where X.Y is the version number of the latest release). If you're using Windows, you can download the command-line tool bsdtar to do this, or you can use a GUI-based tool such as 7-zip. 
- 
-3. Change into the directory created in step 2 (e.g. cd Django-X.Y). 
- 
-4. If you're using Linux, Mac OS X or some other flavor of Unix, enter the command sudo python setup.py install at the shell prompt. If you're using Windows, start a command shell with administrator privileges and run the command python setup.py install. This will install Django in your Python installation's site-packages directory. 
- 
-  python setup.py install 
- 
 ===== Ejemplo aplicacion sin BBDD ===== ===== Ejemplo aplicacion sin BBDD =====
  
Line 509: Line 515:
 } }
 ... ...
 +</code>
 +
 +Flujo habitual para mantener el modelo:
 +
 +<code>
 +1. Change your models (in **models.py**).
 +2. Run **python manage.py makemigrations** to create migrations for those changes
 +3. Run **python manage.py migrate** to apply those changes to the database.
 </code> </code>
  
Line 758: Line 772:
  
   python -c "import tempfile; print tempfile.gettempdir()"   python -c "import tempfile; print tempfile.gettempdir()"
 +  
 +===== LDAP =====
 +
 +pythonhosted.org/django-auth-ldap
 +
 +1. Instalar modulo:
 +
 +  sudo aptitude install python-ldap
 +  sudo pip install django-auth-ldap
 +
 +2. Editar settings:
 +
 +<code>
 +docroot/project1/project1/settings.py
 +
 +# LDAP
 +import ldap
 +from django_auth_ldap.config import LDAPSearch
 +AUTHENTICATION_BACKENDS = (
 +    'django_auth_ldap.backend.LDAPBackend',
 +)
 +AUTH_LDAP_SERVER_URI = "ldaps://ldap.example.com"
 +AUTH_LDAP_BIND_DN = "cn=readonly,dc=example,dc=com"
 +AUTH_LDAP_BIND_PASSWORD = "secret"
 +#AUTH_LDAP_START_TLS = True
 +AUTH_LDAP_USER_SEARCH = LDAPSearch("dc=example,dc=com", ldap.SCOPE_SUBTREE,
 +                                   "(uid=%(user)s)")
 +# LDAP groups
 +from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
 +AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,dc=example,dc=com",
 +    ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
 +)
 +AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
 +AUTH_LDAP_REQUIRE_GROUP = "cn=ldapgroup1,ou=groups,dc=example,dc=com"
 +</code>
 +
 +En este ejemplo nos conectamos via TLS al servidor LDAP "ldap.example.com" y requerimos que el usuario pertenezca al grupo "ldapgroup1", que es un objeto LDAP de tipo "groupOfNames"
 +
 +3. Crear el modelo de base de datos, si es que no lo estaba ya:
 +
 +<code>
 +cd docroot/project1; python manage.py syncdb
 +</code>
 +
 +Contestar a las preguntas.
 +
 +**TODO**: ver si hay alguna forma de evitar este paso, y que se almacenen todos los valores en sesiones.
 +**SOLUCION 1**: sobreescribir _LDAPUser._get_or_create_user() de "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/backend.py"
 +**SOLUCION 2**: escribir nuestro propio backend tomando django_auth_ldap como ejemplo
 +
 +4. Ejemplo de formulario con validacion de usuario:
 +
 +<code>
 +from django.contrib.auth import authenticate
 +
 +def login(request):
 +    ''' Displays/process login form'''
 +    d = {}
 +    if request.method == 'POST': # If the form has been submitted...
 +        d['form'] = LoginForm(request.POST) # A form bound to the POST data
 +        if d['form'].is_valid(): # All validation rules pass
 +            # Process the data in form.cleaned_data
 +            username = d['form'].cleaned_data['username']
 +            password = d['form'].cleaned_data['password']
 +            user = authenticate(username=username, password=password)
 +            if user is not None:
 +                logger.info(user)
 +                return HttpResponse('Success')
 +                if user.is_active:
 +                    login(request, user)
 +                    return HttpResponse('Success')
 +                else:
 +                    return HttpResponse('Disabled account')
 +            else:
 +                return HttpResponse('Invalid login')
 +        else:
 +            d['result'] = "There was an error processing the form"
 +    else:
 +        d['form'] = LoginForm() # An unbound form
 +    return render_to_response('login.html',d,\
 +           context_instance=RequestContext(request))
 +</code>
 +
 +Falta el template y el resto de la vista. Es solo un ejemplo
 +
 +===== Errores =====
 +
 +==== The password is too similar to the username. ====
 +
 +En realidad no es un error, es solo para documentar un atajo para evitar esta restricción a la hora de especificar una contraseña para un nuevo usuario desde la interfaz gráfica del módulo admin.
 +
 +https://stackoverflow.com/a/35330167
 +
 +1. Crear el usuario desde el admin:
 +
 +http://localhost:8000/admin/auth/user/add/
 +
 +2. Iniciar shell
 +
 +  cd /path/django && python manage.py shell
 +  
 +3. Cambiar la contraseña de ese usuario, en este ejemplo "your_user":
 +
 +<code>
 +from django.contrib.auth.models import User
 +user = User.objects.get(username='your_user')
 +user.set_password('simple')
 +user.save()
 +</code>
 +
 +====  Error al crear app ====
 +
 +Comando:
 +
 +<code>
 +python manage.py startapp app1
 +</code>
 +
 +Error:
 +
 +<code>
 +  File "manage.py", line 16
 +    ) from exc
 +         ^
 +SyntaxError: invalid syntax
 +</code>
 +
 +Solución:
 +
 +<code>
 +python3 manage.py startapp app1
 +</code>
informatica/linux/django.1394541178.txt.gz · Last modified: 2015/04/13 20:19 (external edit)