1

pip install django-autocomplete正如django autocomplete的文档所说,我是通过安装的。

然后,我添加了代码,始终遵循给定的文档。

我收到错误:KeyError: Gestion.clientes

而且,当我尝试从 Gestion 应用程序导入视图模块时,它说AttributeError: 'module' object has no attribute 'autocomplete'

似乎我无法导入 Gestion/views.py,因为正在进行循环导入......我试图以多种方式解决这个问题,但我真的被困住了......

这是我的应用程序文件

该应用程序称为“Gestion”,我正在使用 Python2.7 在 vi​​rtualenv 中运行 Django 1.3

Gestion/views.py

# -*- encoding: utf-8 -*-
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage
from django.shortcuts import render_to_response,render
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.core import serializers
import models
from django.db.models import Q
from django.utils import simplejson
from autocomplete.views import AutocompleteView
import forms

autocomplete = AutocompleteView('Gestion')


def home(request):
    return render(request,'index.html')

def facturas(request, cliente=0):
        return render(request,'facturas.html')

def cliente_nuevo(request):
    form = forms.Clientes()
    if request.method == 'POST':
        form = forms.Clientes(request.POST)
        cliente = form.save()
        messages.add_message(request,messages.SUCCESS,'El cliente ha sido creado correctamente')
        return HttpResponseRedirect(reverse('cliente_detalle',args=(cliente.pk,)))
    return render(request,'cliente-nuevo.html',{'form':form})

def clientes(request):

    #Si la petición es de tipo POST, devuelve un listado de cientes en JSON
    if request.method == 'POST':
        if 'q' in request.POST:
            query_build = Q(**{"razon_social__icontains": request.POST['s'] })
            clientes = models.Cliente.objects.filter(query_build)
        else:
            clientes = models.Cliente.objects.all()
        data = serializers.serialize('json', clientes)
        return HttpResponse(data, mimetype='application/json')

    params = request.GET.copy()

    s = None

    if 'page' in params:
        del(params['page'])

    if 's' in params:
        query_build = Q(**{"razon_social__icontains": params['s'] })
        clientes = models.Cliente.objects.filter(query_build)
        s = params['s']
    else:
        clientes = models.Cliente.objects.all()

    paginator = Paginator(clientes, 20)#Clientes por página

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    clientes = paginator.page(page)

    path = params.urlencode()

    return render(request,'clientes.html',{'clientes':clientes,'path':path,'s':s})

def cliente_detalle(request, id):
    cliente = models.Cliente.objects.get(pk = id)
    return render(request,'cliente-detalle.html',{'cliente':cliente})

def cliente_editar(request, id):
    cliente = models.Cliente.objects.get(pk = id)
    form = forms.Clientes(instance=cliente)
    return render(request,'cliente-editar.html',{'form':form, 'cliente':cliente})

def articulo_nuevo(request):
    form = forms.Articulo()
    if request.method == 'POST':
        form = forms.Articulo(request.POST)
        if form.is_valid():
            form.save()
            messages.add_message(request,messages.SUCCESS,'El artículo ha sido creado correctamente')
            return HttpResponseRedirect(reverse('articulos'))
    return render(request,'articulo-nuevo.html',{'form':form})

def articulos(request):
    params = request.GET.copy()
    s = None
    c = None

    if 'page' in params:
        del(params['page'])
    q = Q()
    if 's' in params and params['s']:
        q.add(Q(**{"nombre__icontains": params['s']}), Q.AND)
        q.add(Q(**{"referencia__icontains": params['s']}), Q.OR)
        s = params['s']

    if 'c' in params and params['c']:
        c = params['c']
        q.add(Q(**{"categoria__contains":c}), Q.AND)

    articulos = models.Articulo.objects.filter(q)
    sql = articulos.query

    articulos = list(articulos.order_by('stock'))



    paginator = Paginator(articulos, 2)#Artículos por página

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    articulos = paginator.page(page)
    path = params.urlencode()

    return render(request,'articulos.html',{'lista':list(articulos.object_list),'articulos':articulos, 'path':path, 's':s, 'c':c, 'categorias': models.Articulo.CATEGORIAS, 'sql':sql})

def factura_nueva(request):
    return render(request,'factura-nueva.html')

def pedidos(request):
    return render(request,'pedidos.html')

def nueva_linea_de_pedido(request):
    form = forms.Linea()
    return render(request,'pedido-linea-nueva.html',{'form':form})

def editar_linea_de_pedido(request, linea):
    return render(request,'pedido-linea-editar.html')

Gestion/forms.py

# -*- encoding: utf-8 -*-

from django import forms
import Gestion.models as models
import views
import autocomplete.utils as utils
import autocomplete.widgets as widgets

class Clientes(forms.ModelForm):
    razon_social = forms.CharField(widget=forms.TextInput(attrs={'required':''}),error_messages={'required': 'Escriba la razón social'})
    numero_de_cliente = forms.CharField(widget=forms.TextInput(attrs={'required':''}),required=True,error_messages={'required': 'Escriba el número de cliente'})
    cuit = forms.CharField(widget=forms.TextInput(attrs={'required':''}),error_messages={'required':'Escriba el número de CUIT/CUIL'})
    direccion = forms.CharField(widget=forms.TextInput(attrs={'required':''}),error_messages={'required':'Escriba la dirección'})
    condicion_de_iva = forms.ChoiceField(choices=models.Cliente.CONDICIONES_DE_IVA,error_messages={'required':'Seleccione una condición de IVA'})
    contacto = forms.CharField(required=False)
    class Meta:
        model = models.Cliente

class Articulo(forms.ModelForm):
    nombre = forms.CharField(widget=forms.TextInput(attrs={'required':'','placeholder':'Nombre','class':'span4'}))
    costo = forms.FloatField(widget=forms.TextInput(attrs={'required':'','placeholder':'Costo','class':'span4'}),error_messages={'invalid':'El costo debe ser numérico'})
    categoria = forms.CharField(widget=forms.Select(attrs={'class':'span4'}, choices=models.Articulo.CATEGORIAS))
    referencia = forms.CharField(widget=forms.TextInput(attrs={'required':'','placeholder':'Referencia','class':'span4'}))
    stock = forms.IntegerField(widget=forms.TextInput(attrs={'required':'','placeholder':'Stock','class':'span4'}),error_messages={'invalid':'El stock debe ser un número entero'})
    class Meta:
        model = models.Articulo

class Linea(forms.ModelForm):
    articulo_txt = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Comienze a escribir','class':'span4'}))
    articulo = forms.IntegerField(widget=forms.HiddenInput())
    cliente = utils.autocomplete_formfield('Gestion.clientes',widget=widgets.AutocompleteWidget('Gestion.clientes', view=views.autocomplete))
    class Meta:
        model= models.Linea

管理/urls.py

from django.conf.urls.defaults import patterns, include, url


from Gestion import views
from django.conf import settings
import Gestion.autocomplete_settings

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'imprenta.views.home', name='home'),
    # url(r'^imprenta/', include('imprenta.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^$', views.home, name='home'),
    url(r'^facturas/$', views.facturas, name='facturas'),
    url(r'^facturar/$', views.factura_nueva, name='facturar'),
    url(r'^clientes/nuevo/$', views.cliente_nuevo, name='cliente-nuevo'),
    url(r'^clientes/$', views.clientes, name='clientes'),
    url(r'^clientes/detalle/([0-9]+)$', views.cliente_detalle, name='cliente_detalle'),
    url(r'^cliente/([0-9]+)/facturas/$', views.facturas, name='cliente_facturas'),
    url(r'^clientes/editar/([0-9]+)$', views.cliente_editar, name='cliente_editar'),
    url(r'^articulos/$', views.articulos, name='articulos'),
    url(r'^articulos/nuevo/$', views.articulo_nuevo, name='articulo_nuevo'),
    url(r'^pedidos/$', views.pedidos, name='pedidos'),
    url(r'^pedidos/lineas/nueva/$', views.nueva_linea_de_pedido, name='pedidos-linea-nueva'),
    url(r'^pedidos/lineas/editar/([0-9]+)$', views.editar_linea_de_pedido, name='pedidos-linea-editar'),
    url(r'^autocomplete/', include(views.autocomplete.urls)),
) + patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT}))
4

1 回答 1

0

您几乎不应该views导入forms. 表单在视图中使用,反之亦然。我会autocomplete = AutocompleteView('Gestion')进入一些单独的模块(例如,gestion.autocomplete)并从那里导入。

PS另外请注意Python中的模块以小写命名,所以应该是gestion,而不是Gestion

于 2013-07-17T18:19:54.150 回答