在Django 1.5中查询表单

2024-05-16 19:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要对我在Django的表单a执行一个CRUD操作,但我不知道如何实现这一点。我的意思是有不同的情况和方法,我在寻找什么。你知道吗

考虑以下形式:

class UsuarioFidetel(models.Model):
"""
Modelo de usuario fidetel
"""

usuario = models.CharField(max_length=30)
id_usuario = models.IntegerField()
nombre = models.CharField(max_length=255, null=True)
apellido = models.CharField(max_length=255, null=True)
tipo_cedula = models.CharField(max_length=1, null=True)
cedula = models.CharField(max_length=9, null=True)
fecha_nacimiento = models.DateField(null=True, blank=True)
sexo = models.CharField(max_length=1, null=True)
correo = models.EmailField(max_length=254, null=True)
estado_civil = models.CharField(max_length=1, null=True)

def __unicode__(self):
    return self.nombre

db上有几个用户存储了这些字段。现在,我需要从一个不同的窗体中查询这个,并显示用户的数据,甚至编辑这个数据/用户。你知道吗

我已经穿上了型号.py,模板上的所有内容都正常,但我需要进行此查询,我知道我应该使用以下内容:

usuarios = UsuarioFidetel.objects.all().order_by("nombre").values('nombre')

但是我对如何实现这个很困惑,或者我应该使用queryset?你知道吗

任何例子或想法都是受欢迎的。你知道吗

提前谢谢!你知道吗

更新

我的表单.py地址:

class FormularioUsuarioFidetel(FormularioPersona):
"""
Clase que contiene el formulario que permite ingresar y modificar los 
datos del usuario de fidetel
"""    
usuariofide = forms.CharField()
sexo = ChoiceField(required=True, 
                   choices=SEXO_OPCIONES, 
                   error_messages={'required': 'El Sexo es un campo obligatorio'})
estado_civil = ChoiceField(required=True, 
                           choices=ESTADO_CIVIL_OPCIONES, 
                           error_messages={'required': 'El Estado Civil es un campo obligatorio'})

class Meta:
    model = UsuarioFidetel
    fields = ('nombre', 'apellido', 'tipo_cedula', 'cedula', 'correo', 'sexo', 'estado_civil', 'fecha_nacimiento')

def __init__(self, *args, **kwargs):
    super(FormularioUsuarioFidetel, self).__init__(*args, **kwargs)
    self.fields['fecha_nacimiento'].widget.attrs = {'style':'width: 90px', 
                                                  'maxlength':'10'}
    self.fields['fecha_nacimiento'].required = True
    self.fields['fecha_nacimiento'].error_messages = {'required': 'La Fecha de Nacimiento es un campo obligatorio'}

def clean_fecha_nacimiento(self):
    """
    Método que valida que la fecha de nacimiento no sea posterior a la fecha 
    actual

    @return: Un mensaje de error si la fecha de nacimiento es posterior a la 
    fecha actual
    """
    fecha_nacimiento = str(self.cleaned_data['fecha_nacimiento'])

    if fecha_nacimiento > str(datetime.datetime.now().date()):
        raise forms.ValidationError(u"La fecha de nacimiento no puede ser posterior a la fecha actual")

    return self.cleaned_data['fecha_nacimiento']

我的视图.py你知道吗

def consultar_usuario_fidetel(request):
"""
Muestra el formulario de consulta de datos del usuario de fidetel

@return: El formulario de consulta de datos del usuario de fidetel
"""

usuario_fidetel = request.session['usuario_fidetel']

if(not usuario_fidetel.tipo_cedula):
    return render_to_response('fidetel/inicio.html', 
                              { }, 
                              context_instance=RequestContext(request))

sexo = dict(SEXO_OPCIONES)[usuario_fidetel.sexo]
estado_civil = dict(ESTADO_CIVIL_OPCIONES)[usuario_fidetel.estado_civil]

return render_to_response('fidetel/consultar_usuario_fidetel.html', 
                          { 'usuario_fidetel': usuario_fidetel,
                            'sexo': sexo,
                            'estado_civil': estado_civil }, 
                          context_instance=RequestContext(request))

@autenticacion_fidetel_requerida
@permiso_requerido([PERMISOS_FONDO['MODIFICAR_USUARIO_FIDETEL']])

让我更好地解释一下我自己,通过这个表单和视图,我可以编辑登录到webapp的用户的数据,现在,我需要的是,将所有从modelUsuarioFidetel存储的用户加载到db中,不管谁登录到应用程序,可能是按它的名称或其他方式搜索。。。你知道吗

如果你需要进一步的解释,请告诉我,谢谢。你知道吗


Tags: selftruemodelsdenulllengthmaxcharfield
2条回答

我不知道你在问什么,因为在django中你可以使用generic views,这将使你的许多日常工作自动化;你所需要做的只是适当地配置它们。你知道吗

因为已经有了一个表单,所以可以使用^{}, ^{}, ^{}来处理CRUD操作。你知道吗

要简单地列出所有对象,请使用^{},如下所示:

views.py中:

from django.views.generic import ListView
from .models import UsuarioFidetel

class UsarioList(ListView):
    model = UsuarioFidetel
    template_name = 'all_list.html'

urls.py中:

from django.conf.urls import patterns, url
from yourapp.views import UsarioList

urlpatterns = patterns('',
    url(r'^usario/$', UsarioList.as_view()),
)

all_list.html中,您将得到一个变量object_list,它将是所有对象的列表,精确地分页:

{% if object_list %}
    {% for obj in object_list %}
       {{ obj }}
    {% endfor %}
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_previous %}
                    <a href="/usario?page={{ page_obj.previous_page_number }}">&lt;</a>
                {% endif %}
                <span class="page-current">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                </span>
                {% if page_obj.has_next %}
                    <a href="/usario?page={{ page_obj.next_page_number }}">&gt;</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
{% else %}
    <p>No records found</p>
{% endif %}

你知道吗视图.py #获取所有用户并注入用户.htm你知道吗

 def users(request):    
    users=UsuarioFidetel.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)

在用户.html你知道吗

删除和编辑具有2个链接的所有用户的列表

{% for user in users %}
<li>{{user.usuario}}<span>{{user.apellido}}</span></li> 
<a  href="{% url 'editUser' user.id %} "></a>
<a  href="{% url 'deletetUser' user.id %}"></i></a>                 
{% endfor %}

你现在知道这个例子了吗

相关问题 更多 >