django-autocomplete key error - python

I installed via pip install django-autocomplete, as the django autocomplete's documentation said.
Then, i added the code, always following the documentation given.
I get the error: KeyError: Gestion.clientes
and also, when i try to import the views module from Gestion app, it says AttributeError: 'module' object has no attribute 'autocomplete'
It seems like i cannot import Gestion/views.py, since there's a circular import going on... i tried to attack this issue in many ways, but i'm really stucked...
Here's my app files
The app is called "Gestion", i'm running Django 1.3 in virtualenv with Python2.7
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
Gestion/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}))

You should almost never import views into forms. Forms are used in views, not vice versa. I'd move autocomplete = AutocompleteView('Gestion') into some separate module (for example, gestion.autocomplete) and imported from there.
P.S. Also please note that modules in Python are named in lowercase, so it should be gestion, not Gestion

Related

The view products.views.get_product didn't return an HttpResponse object. It returned None instead

ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/
The view products.views.get_product didn't return an HttpResponse object. It returned None instead.
how can i solve this problem please help me
`
from django.shortcuts import render,redirect
from products.models import Product
from accounts.models import *
from django.http import HttpResponseRedirect
from products.models import *
from django.utils.timezone import datetime
# Create your views here.
def get_product(request, slug):
product = Product.objects.get(slug=slug)
# comment = Comment.objects.get(slug=slug)
if request.method == "POST":
star = request.POST.get('star')
name = request.user.first_name
body = request.POST.get('body')
review = Comment(star=star, name=name,body=body,date_added = datetime.today())
review.product = product
review.save()
return redirect(f'/product/{slug}', slug=product.slug)
try:
context = {'product': product, }
if request.GET.get('size'):
size = request.GET.get('size')
price = product.get_product_price_by_size(size)
context['selected_size'] = size
context['updated_price'] = price
return render(request, 'product\product.html' , context = context)
except Exception as e:
print(e)
`
i am making a ecommerce website and i add review option then i got this error
You got this error because return is inside if statement.
I have modified this:
try:
context = {'product': product, }
if request.GET.get('size'):
size = request.GET.get('size')
price = product.get_product_price_by_size(size)
context['selected_size'] = size
context['updated_price'] = price
except Exception as e:
print(e)
return render(request, 'product\product.html', context)

Getting 405 http error in POST on Django, the is problem in the urls?

Getting 405 status after using POST method in this django aplication
#urls
"""Configuracoes de URL dos Resultados das Buscas
https://docs.djangoproject.com/en/3.1/topics/http/urls/
"""
from django.conf.urls import url
from django.urls import path
from . views import BuscaHorarios, AgendaHorario
app_name = "agendamento"
urlpatterns = [
url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$',
AgendaHorario.as_view(),
name='horarios',
),
url('/', AgendaHorario.as_view(), name="agenda_horario"),
]
I think the problem occurs over here, but i'm not sure
##forms
from django.forms import Form, CharField, EmailField, EmailInput, TextInput
class AgendaHorarioForm(Form):
nome_paciente = CharField(required=True, widget=TextInput(
attrs={'placeholder': 'Digite seu nome completo',
'class': 'form-control', 'label_tag': 'Nome do paciente'}))
email_paciente = EmailField(widget=EmailInput(attrs={'placeholder': 'Digite seu e-mail', 'class': 'form-control', 'label_tag': 'E-mail'}))
telefone_paciente = CharField(required=True, widget=TextInput(
attrs={'placeholder': 'Digite seu telefone com DDD',
'data-mask': '(00) 00000-0000',
'class': 'form-control',
'label_tag': 'Telefone com DDD'}))
views
class AgendaHorario(View):
form_class_agenda = AgendaHorarioForm
paciente = {}
prestadorunidade = None
prestadorservicos = None
servicoregioes = None
agenda_service = None
horario_marcado = None
def get_context_data(self, **kwargs):
print('a')
context = super().get_context_data(**kwargs)
context['prestadorunidade'] = self.prestadorunidade
context['prestadorservicos'] = self.prestadorservicos
context['horario_marcado'] = self.horario_marcado
context['paciente'] = self.paciente
print('a')
return context
def post(self, *args, **kwargs):
print('b')
if self.request.is_ajax and self.request.method == "POST":
form = self.form_class_agenda(self.request.POST)
if form.is_valid():
post_data = form.cleaned_data
self.paciente['nome'] = post_data['nome_paciente']
self.paciente['email'] = post_data['email_paciente']
self.paciente['telefone'] = post_data['telefone_paciente']
lista_unidades = list(cache.get('PrestadorUnidades', PrestadorUnidades.objects.values()))
unidadeid = int(self.request.POST.get('prestadorunidadeid'))
self.prestadorunidade = [item for item in lista_unidades if item['unidadeid'] == unidadeid][0]
lista_prestadorservicos = list(cache.get('PrestadorServicos', PrestadorServicos.objects.values()))
prestadorservicosid = int(self.request.POST.get('prestadorservicosid'))
self.prestadorservicos = [
item for item in lista_prestadorservicos if item['prestadorservicoid'] == prestadorservicosid][0]
lista_servicos = list(cache.get('ServicosRegioesCorpo', ServicosRegioesCorpo.objects.values()))
self.servicoregioes = [item for item in lista_servicos if item['idservicosregioes']
== self.prestadorservicos['idservicosregioes_fk_id']][0]
servico = ServicosRegioesCorpo.objects.get(
idservicosregioes=self.prestadorservicos['idservicosregioes_fk_id'])
horario = self.request.POST.get('horario-escolhido')
self.horario_marcado = refatora_data(horario)
self.horario_marcado = datetime.datetime.strptime(self.horario_marcado, '%Y-%m-%dT%H:%M')
prestadorunidade_calendar_list = list(cache.get('Calendar', Calendar.objects.values()))
prestadorunidade_calendar = [item for item in prestadorunidade_calendar_list if item['id']
== self.prestadorunidade['calendar_id_fk']][0]
prestadorunidade_calendar_obj = Calendar.objects.get(id=self.prestadorunidade['calendar_id_fk'])
self.agenda_service = GoogleCalendarService(
prestadorunidade_calendar, prestadorunidade_calendar_obj, self.prestadorservicos)
self.marcar_servico(self.horario_marcado)
msg_sucesso = f'%s agendado com sucesso para %s. Anote na sua agenda!' % (
servico, self.paciente['nome'])
return JsonResponse({"msg_sucesso": msg_sucesso, "horario_marcado": horario}, status=200)
else:
return JsonResponse({"error": form.errors}, status=400)
return JsonResponse({"error": ""}, status=400)
def marcar_servico(self, horario):
print('c')
servico = ServicosRegioesCorpo.objects.get(
idservicosregioes=self.prestadorservicos['idservicosregioes_fk_id'])
summary = f'%s com paciente %s. Contato: %s ou %s' % (str(servico),
self.paciente['nome'],
self.paciente['telefone'],
self.paciente['email'])
lista_bairros = list(cache.get('Bairros', Bairros.objects.values()))
bairro = [item for item in lista_bairros if item['bairroid'] == self.prestadorunidade['bairroid_fk_id']][0]
location = f'%s %i, %s\n%s, %s\n%s' % (self.prestadorunidade['logradourounid'],
self.prestadorunidade['numerounid'],
self.prestadorunidade['complementounid'],
bairro['bairro'],
bairro['cidade'],
self.prestadorunidade['cep'])
descricao = 'Agendado pelo Saúde Pra Já.'
self.agenda_service.marcar_evento(summary, location, horario, descricao)
html simplified
<form id="schedule-form" action="" method="POST">
<input type="submit" id="submit-horario" value="Confirmar"/>
Am i seting my urls wrong ?
Is the error ou the views.py file ?
The only message i get in the console is: POST /agendamento/11749/1341/ HTTP/1.1" 405 0
When i run this post in Insomnia i get http status 403

Django 1.10 redirect view not working

My redirect to another view is not working in django 1.10
Views.py
from django.shortcuts import render, redirect
# Create your views here.
from forms import DocumentForm
from models import Document
from django.apps import apps
myapp = apps.get_app_config('django_celery_results')
myapp.models.TASK_MODEL = myapp.models['taskresult']
def tasks_view(request):
tasks = TASK_MODEL.objects.all()
return render(request, 'saved.html', {'tasks': tasks})
def SaveDocument(request):
saved = False
if request.method == "POST":
#Get the posted form
MyDocumentForm = DocumentForm(request.POST, request.FILES)
if MyDocumentForm.is_valid():
print 'It enters here'
document = Document()
document.name = MyDocumentForm.cleaned_data["name"]
document.doc = request.FILES["document"]
print document.doc
print document.name
print 'request type', request.method
document.save()
saved = True
return redirect('tasks_view')
else:
print 'Fails'
else:
MyDocumentForm = DocumentForm()
return render(request, 'saved.html', locals())
urls.py
from django.conf.urls import url
from django.views.generic import TemplateView
from core.views import *
urlpatterns = [
url(r'profile/',TemplateView.as_view(
template_name = 'profile.html')),
url(r'saved/', SaveDocument, name = 'SaveDocument'),
url(r'check/', tasks_view, name = 'tasks_view,')
]
I do not understand why do i always get this exception in Reverse for 'tasks_view' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
The url redirects to NoReverseMatch at /my_app/saved/. Why doesnt it redirect to the tasks view and goes to /my_app/check/ instead?
from django.conf.urls import url
from django.views.generic import TemplateView
from core.views import *
urlpatterns = [
url(r'profile/',TemplateView.as_view(
template_name = 'profile.html')),
url(r'saved/', SaveDocument, name = 'SaveDocument'),
url(r'check/', tasks_view, name = 'tasks_view')
]
Here you have small mistake in your code, you added coma at url(r'check/', tasks_view, name = 'tasks_view')
now this will definitely work.
At first reverse("view_name") after redirect
from django.core.urlresolvers import reverse
def SaveDocument(request):
saved = False
if request.method == "POST":
#Get the posted form
MyDocumentForm = DocumentForm(request.POST, request.FILES)
if MyDocumentForm.is_valid():
print 'It enters here'
document = Document()
document.name = MyDocumentForm.cleaned_data["name"]
document.doc = request.FILES["document"]
print document.doc
print document.name
print 'request type', request.method
document.save()
saved = True
return redirect(reverse('tasks_view'))
else:
print 'Fails'
else:
MyDocumentForm = DocumentForm()
return render(request, 'saved.html', locals())

View function not getting called in Django

Here's the view.py. show_checkout is called and runs all the way to return HttpResponseRedirect('/receipt/'), but for some reason, receipt view isn't being fired. none of the print statements are working:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from ecomstore.checkout.forms import CheckoutForm
from ecomstore.checkout.models import Order, OrderItem
from ecomstore.checkout import checkout
from ecomstore.cart import cart
from django.core.context_processors import csrf
# Create your views here.
def show_checkout(request, template_name='checkout/checkout.html'):
c = {}
c.update(csrf(request))
if cart.is_empty(request):
cart_url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(cart_url)
if request.method == 'POST':
postdata = request.POST.copy()
form = CheckoutForm(postdata)
if form.is_valid():
response = checkout.process(request)
order_number = response.get('order_number',0)
print 'this is the order number: ' + str(order_number)
error_message = response.get('message','')
if order_number:
request.session['order_number'] = order_number
# receipt_url = urlresolvers.reverse('checkout_receipt')
print request.session['order_number']
return HttpResponseRedirect('/receipt/')
else:
error_message = 'Correct the errors below'
else:
form = CheckoutForm()
page_title = 'Checkout'
return render_to_response(template_name, locals(), context_instance= RequestContext(request))
##Currently this doesn't seem to be running
def receipt(request, template_name='checkout/receipt.html'):
order_number = request.session.get('order_number','')
print 'this is receipt order number: ' + str(order_number)
if order_number:
print 'in order_number'
order = Order.objects.filter(id=order_number)[0]
order_items = OrderItem.objects.filter(order=order)
del request.session['order_number']
else:
print 'not in order number'
cart_url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(cart_url)
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Here is the checkout.urls:
from django.conf.urls.defaults import *
from ecomstore import settings
urlpatterns = patterns('ecomstore.checkout.views',
(r'^$','show_checkout',{'template_name':'checkout/checkout.html','SSL':settings.ENABLE_SSL},'checkout'),
(r'^receipt/$','receipt',{'template_name':'checkout/receipt.html','SSL':settings.ENABLE_SSL},'checkout_receipt'),
)
and the urls.py:
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ecomstore.views.home', name='home'),
# url(r'^ecomstore/', include('ecomstore.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)),
(r'^', include('catalog.urls')),
(r'^cart/$', include('cart.urls')),
(r'^checkout/$', include('checkout.urls')),
(r'^receipt/$', include('checkout.urls')),
)
IMPORTANT: Also it's currently being forwarded to localhost/cart
In your main urls.py, don't use "$" in the regex. That seems to have fixed it for me.
My guess would be that you mean /receipt/receipt

TypeError in Django

Have this error while creating tutorial:
http://img718.imageshack.us/img718/2194/unled2bh.jpg
Have no freakin idea what's wrong. It's displays when i added this modifications:
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'sklep.context_processors.koszyk'
)
EMAIL_PORT = 1025
EMAIL_SKLEPU = 'sklep#sklep-z-koszulkami.pl'
sklep/urls.py
url(r'^koszyk/$', 'koszyk', name="sklep_koszyk"),
url(r'^koszyk/dodaj/(\d+)/$', 'koszyk_dodaj', name="sklep_koszyk_dodaj"),
sklep/views.py
# coding: utf-8
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.core.mail import send_mail
from django.template import Context, loader
from django.conf import settings
from sklep.models import Produkt
from sklep.forms import ZamowienieForm
def koszyk(request):
koszyk = request.session.get('koszyk', [])
produkty = list(Produkt.objects.filter(pk__in=koszyk))
if request.method == 'POST':
formularz = ZamowienieForm(request.POST)
if formularz.is_valid():
dane = formularz.cleaned_data
tresc = loader.get_template('sklep/zamowienie.txt').render(Context({'produkty': produkty, 'dane': dane}))
send_mail('Potwierdzenie zakupu', tresc, settings.EMAIL_SKLEPU, [dane['email']])
send_mail(u'Zamówienie', tresc, dane['email'], [settings.EMAIL_SKLEPU])
del request.session['koszyk']
return HttpResponseRedirect(reverse('sklep_koszyk'))
else:
formularz = ZamowienieForm()
if koszyk:
kontekst = {'koszyk': produkty, 'formularz': formularz}
else:
kontekst = {'koszyk': []}
return direct_to_template(request, 'sklep/koszyk.html', extra_context = kontekst)
def koszyk_dodaj(request, id_produktu):
koszyk = request.session.get('koszyk', [])
if int(id_produktu) not in koszyk:
koszyk.append(int(id_produktu))
request.session['koszyk'] = koszyk
return HttpResponseRedirect(reverse('sklep_koszyk'))
context_processors.py
def koszyk(request): return {'stan_koszyka':len(request.session.get('koszyk', []))}
And i have added two templates.
Error shows up, when i enter /sklep/koszyk/ or /sklep/koszyk/dodaj/1/ URL...
You need to use the full path to your views in urls.py:
url(r'^koszyk/$', 'app_name.views.koszyk', name="sklep_koszyk"),
url(r'^koszyk/dodaj/(\d+)/$', 'app_name.views.koszyk_dodaj', name="sklep_koszyk_dodaj"),

Categories

Resources