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
Related
I have a situation here where I am creating a record from a view
def index(request):
if request.method == "POST":
order_number = request.POST.get('order_number')
post_code = request.POST.get('post_code')
print(order_number)
print(post_code)
if order_number and post_code:
n = page1.objects.create(orderNumber=order_number, postCode=post_code)
n.save()
id = n.id
return redirect("page1:waiting")
return render(request,"page1/index.html")
And upon creating the record I am redirecting the user to another page with id.
127.0.0.1/page1/waiting/fb65-io98-.....
from django.urls import path
from . import views
app_name = 'page1'
urlpatterns = [
path('', views.index, name="amounts"),
path('waiting/<str:pk>', views.waitReply, name="waiting"),
]
View for Second URL
def waitReply(request,pk):
get_amount = page1.objects.get(id=pk)
context = {'get_amount':get_amount}
return render(request, "page1/payment-confirm.html", context)
But the problem is how do I attach/generate/get the id in index view and send it for the waitReply view
I can get the latest ID through n.id
Kindly help.
Use reverse with args in HttpResponseRender.
return HttpResponseRender(reverse('page1:waiting' args=[id]))
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)
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())
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')),
)
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"),