Published on InterSystems Developer Community (https://community.intersystems.com)

Inicio > Introducción a Django - 2ª parte

Artículo
Ricardo Paiva · 21 nov, 2022 Lectura de 8 min

Introducción a Django - 2ª parte

En la primera parte de este artículo he mostrado cómo empezar un nuevo proyecto en Django, y cómo definir nuevos modelos y añadir modelos ya existentes.

En esta publicación, voy a mostrar un Panel de Administración (disponible con la configuración predeterminada) y cómo puede ser útil.

Nota importante: si intentáis reproducir los pasos de este artículo, no funcionará para vosotros. Porque mientras escribía la publicación he realizado varios ajustes en el proyecto django-iris, e incluso en el driver DB-API de InterSystems, para arreglar algunos problemas ahí también, y creo que el driver aún está en desarrollo y habrá un driver más estable en el futuro. Así que vamos a asumir que este artículo solo explica cómo podría ser si tuviéramos todo terminado.

Vamos a volver a nuestro código y ver lo que tenemos en urls.py, el principal punto de entrada de todas las solicitudes web.

"""main URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/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.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

Se puede ver que ya hay una URL admin definida ahí.

Empezamos el servidor de desarrollo, por comando

python manage.py runserver

Si se va por la URL http://localhost:8000/admin, aparece el formulario de inicio de sesión de Django administration 

Para entrar aquí, hace falta un usuario, que podemos crear con este comando

$ python manage.py createsuperuser
Username (leave blank to use 'daimor'): admin
Email address: admin@example.com
Password: 
Password (again): 
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

Ya podemos usar ese usuario y contraseña. Está bastante vacío ahora, pero ya da acceso a Groups y Users.

Más datos

Previamente ya he instalado el paquete post-and-tags con zpm. Lo podéis instalar también

zpm "install posts-and-tags"

Ahora podemos obtener los modelos para todas las tablas (community.post, community.comment, community.tag) instaladas con este paquete

$ python manage.py inspectdb community.post community.comment community.tag > main/models.py

Esto producirá un archivo un poco largo, así que lo he puesto en este desplegable:

 
main/models.py
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models


class CommunityPost(models.Model):
    acceptedanswerts = models.DateTimeField(db_column='AcceptedAnswerTS', blank=True, null=True)  # Field name made lowercase.
    author = models.CharField(db_column='Author', max_length=50, blank=True, null=True)  # Field name made lowercase.
    avgvote = models.IntegerField(db_column='AvgVote', blank=True, null=True)  # Field name made lowercase.
    commentsamount = models.IntegerField(db_column='CommentsAmount', blank=True, null=True)  # Field name made lowercase.
    created = models.DateTimeField(db_column='Created', blank=True, null=True)  # Field name made lowercase.
    deleted = models.BooleanField(db_column='Deleted', blank=True, null=True)  # Field name made lowercase.
    favscount = models.IntegerField(db_column='FavsCount', blank=True, null=True)  # Field name made lowercase.
    hascorrectanswer = models.BooleanField(db_column='HasCorrectAnswer', blank=True, null=True)  # Field name made lowercase.
    hash = models.CharField(db_column='Hash', max_length=50, blank=True, null=True)  # Field name made lowercase.
    lang = models.CharField(db_column='Lang', max_length=50, blank=True, null=True)  # Field name made lowercase.
    name = models.CharField(db_column='Name', max_length=250, blank=True, null=True)  # Field name made lowercase.
    nid = models.IntegerField(db_column='Nid', primary_key=True)  # Field name made lowercase.
    posttype = models.CharField(db_column='PostType', max_length=50, blank=True, null=True)  # Field name made lowercase.
    published = models.BooleanField(db_column='Published', blank=True, null=True)  # Field name made lowercase.
    publisheddate = models.DateTimeField(db_column='PublishedDate', blank=True, null=True)  # Field name made lowercase.
    subscount = models.IntegerField(db_column='SubsCount', blank=True, null=True)  # Field name made lowercase.
    tags = models.CharField(db_column='Tags', max_length=350, blank=True, null=True)  # Field name made lowercase.
    text = models.TextField(db_column='Text', blank=True, null=True)  # Field name made lowercase.
    translated = models.BooleanField(db_column='Translated', blank=True, null=True)  # Field name made lowercase.
    type = models.CharField(db_column='Type', max_length=50, blank=True, null=True)  # Field name made lowercase.
    views = models.IntegerField(db_column='Views', blank=True, null=True)  # Field name made lowercase.
    votesamount = models.IntegerField(db_column='VotesAmount', blank=True, null=True)  # Field name made lowercase.
    class Meta:
        managed = False
        db_table = 'community.post'
class CommunityComment(models.Model):
    id1 = models.CharField(db_column='ID1', primary_key=True, max_length=62)  # Field name made lowercase.
    acceptedanswerts = models.DateTimeField(db_column='AcceptedAnswerTS', blank=True, null=True)  # Field name made lowercase.
    author = models.CharField(db_column='Author', max_length=50, blank=True, null=True)  # Field name made lowercase.
    avgvote = models.IntegerField(db_column='AvgVote', blank=True, null=True)  # Field name made lowercase.
    correct = models.BooleanField(db_column='Correct', blank=True, null=True)  # Field name made lowercase.
    created = models.DateTimeField(db_column='Created', blank=True, null=True)  # Field name made lowercase.
    hash = models.CharField(db_column='Hash', max_length=50, blank=True, null=True)  # Field name made lowercase.
    id = models.IntegerField(db_column='Id')  # Field name made lowercase.
    post = models.CharField(db_column='Post', max_length=50, blank=True, null=True)  # Field name made lowercase.
    text = models.TextField(db_column='Text', blank=True, null=True)  # Field name made lowercase.
    texthash = models.CharField(db_column='TextHash', max_length=50, blank=True, null=True)  # Field name made lowercase.
    type = models.CharField(db_column='Type', max_length=50)  # Field name made lowercase.
    votesamount = models.IntegerField(db_column='VotesAmount', blank=True, null=True)  # Field name made lowercase.
    class Meta:
        managed = False
        db_table = 'community.comment'
        unique_together = (('type', 'id'),)


class CommunityTag(models.Model):
    description = models.TextField(db_column='Description', blank=True, null=True)  # Field name made lowercase.
    name = models.TextField(db_column='Name', primary_key=True)  # Field name made lowercase.
    class Meta:
        managed = False
        db_table = 'community.tag'

El dashboard de administración en Django, se puede extender mediante desarrollo. Y es posible añadir algunas tablas más. Para hacerlo, tenemos que añadir un nuevo archivo llamado main/admin.py. He añadido unos pocos comentarios directamente en el código, para explicar algunas líneas.

from django.contrib import admin

# immport our community models for our tables in IRIS
from .models import (CommunityPost, CommunityComment, CommunityTag)
# register class which overrides default behaviour for model CommunityPost
@admin.register(CommunityPost)
class CommunityPostAdmin(admin.ModelAdmin):
  # list of properties to show in table view
  list_display = ('posttype', 'name', 'publisheddate')
  # list of properties to show filter for on the right side of the tablee
  list_filter = ('posttype', 'lang', 'published')
  # default ordering, means from the latest date of PublishedDate
  ordering = ['-publisheddate', ]

@admin.register(CommunityComment)
class CommunityCommentAdmin(admin.ModelAdmin):
  # only this two fields show, (post is numeric by id in table post)
  list_display = ('post', 'created')
  # order by date of creation
  ordering = ['-created', ]

@admin.register(CommunityTag)
class CommunityTagAdmin(admin.ModelAdmin):
  # not so much to show
  list_display = ('name', )

Portal extendido

Vamos a volver a nuestra página de administración en Django, y vemos algunas cosas nuevas ahí

A la derecha se ve el panel de filtros, y lo que es importante es que tiene todos los posibles valores de cada campo. 

Desafortunadamente, InterSystems SQL no es compatible con la funcionalidad LIMIT, OFFSET. Y Django no es compatible con TOP. Así que se mostrará aquí la paginación, pero no funciona. Y no hay forma de hacerla funcionar por el momento, y no creo que nunca funcione, lamentablemente.

Se puede incluso analizar el objeto, y Django mostrará el formulario, con los tipos de campo correctos. (Nota: Este conjunto de datos no contiene datos en el campo Text)

Objeto Comments

 
Problemas esperados con licencias de la Community Edition
Si trabajáis con la Community Edition, podéis encontraros este problema, así es como se ve cuando todas las conexiones están ocupadas, puede pasar muy rápido. Y si véis que la respuesta del servidor es bastante larga, seguramente es el caso, porque IRIS no responde rápido en este caso; por alguna razón lleva mucho tiempo.

Incluso cuando IRIS dice, te queda capacidad

No permite más de 5 conexiones, así que necesitaréis terminar uno o más procesos para que funcione. O reiniciar el servidor de Django

En desarrollo, también se puede limitar el servidor Django al modo no threading, y funcionará en un proceso. Y no debería solicitar más conexiones a IRIS.

python manage.py runserver --nothreading
#Python #InterSystems IRIS

URL de fuente:https://es.community.intersystems.com/post/introducci%C3%B3n-django-2%C2%AA-parte