TypeError in Django - python

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"),

Related

trying to get my views.py and urls.py to work properly

I am currently trying to get my database that I created to display on my Djnago server however I keep getting errors for my FruitModel saying that there are no objects however I have created objects for the FruitModel in my datbase using "record = FruitModel.objects.create(name='banana', price='4.00').
I am also getting an unable to display error for my urls when I loaded up my server.
Here is my code for
Views.py and for urls.py:
(views.py code)
from django.shortcuts import render, redirect
from catalog.models import FruitModel
from catalog.forms import FruitForm
from django.http import HttpResponse
# Create your views here.
def FruitView(request):
fruit = FruitModel.objects.all()
html = ''
for fruits in fruit:
var = f'<li> {fruits.name} </li><br>'
html = html + var
return HttpResponse(html,status = 200)
def FruitIDView(request,name):
fruits = FruitModel.objects.get(name = f'{fruits.name}')
html = f'<h2>{fruits.name}</h2><br>'
return HttpResponse(html, status=200)
(urls.py code)
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from catalog import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^FruitView/?$', views.FruitView),
]
You need this changes:
#urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^FruitView/?$', views.FruitView),
path('FruitIDView/<str:naam>', views.FruitIDView), #use path instead of url
]
#models.py (if not created)
class FruitModel(models.Model):
name = models.CharField(max_length=200,null=True,blank=True)
price = models.IntegerField()
#views.py
def FruitView(request):
fruit = FruitModel.objects.all()
html = ''
for fruits in fruit:
var = f'<li> {fruits.name} </li><br>'
html = html + var
return HttpResponse(html,status = 200)
def FruitIDView(request,naam):
fruits = FruitModel.objects.get(name = naam) #how can you use fruits.name here
html = f'<h2>{fruits.name}</h2><br>'
return HttpResponse(html, status=200)
#admin.py (if not created)
from .models import *
# Register your models here.
admin.site.register(FruitModel)

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())

django-autocomplete key error

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

How to create callback URL in Django PuSH

I am using Django-PuSH (PubSubHubPub) for my Blogger's Blog.
Now, I read the documentation and could make simple code. However, the document never mentioned anywhere to enter a callback URL!
Here is the simple code.
# hubserver.py
#receiver(updated)
def listener(notification, **kwargs):
e = []
for entry in notification.entries:
e.append(entry.title)
for link in e:
db = entries( url = link )
db.save(force_insert=True)
from django.shortcuts import render_to_response
from django_push.subscriber.models import Subscription
from models import mydata
# views
def bloghub (request):
subscription = Subscription.objects.subscribe("http://myblog.blogspot.in//feeds/posts/default",
"http://pubsubhubbub.appspot.com")
db = mydata.objects.all()
lis = [i.url for i in db]
context = {"lis" : lis}
return render_to_response("home.html", context)
[1]: http://django-push.readthedocs.org
# urls.py
urlpatterns = patterns('',
url(r'^$', views.bloghub ),
url(r'^subscriber/', include('django_push.subscriber.urls')),
)

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

Categories

Resources