I am getting error : 'str' object has no attribute 'method' . See my code below :
#csrf_exempt
def completepayment(request):
varerr =''
plist = []
if request.method == 'POST':
try:
nid = request.POST['txnref']
except MultiValueDictKeyError:
varerr ="Woops! Operation failed due to server error. Please try again later."
return render(request, 'uportal/main.html', {'varerr':varerr})
# Fetching member details
trym = Transactions.objects.get(TransRef=nid)
amount = trym.Amount
famt = int(amount * 100)
product_id = 48
salt = '4E6047F9E7FDA5638D29FD'
hash_object = hashlib.sha512(str(product_id)+str(nid)+str(famt))
hashed = hash_object.hexdigest()
url = 'https://bestng.com/api/v1/gettransaction.json?productid=pdid&transactionreference=nid&amount=famt'
raw = urllib.urlopen(url)
js = raw.readlines()
#js_object = simplejson.loads(js)
res = simplejson.dumps(js)
for item in res:
rcode = item[0]
#rdesc = item[1]
#preff = item[2]
thisresp = completepayment(rcode)
plist.append(thisresp)
else:
varerr ="Woops! Operation failed due to server error. Please try again later."
return render(request, 'uportal/main.html', {'plist':plist, 'varerr':varerr, 'completepayment':'completepayment'})
In summary I am trying to accept and use HTTP POST value from an external API. Value is showing when I inspect element but DJANGO not retrieving. Please help.
Here is my urls.py
from django.conf.urls import patterns, url
from views import *
from django.views.generic import RedirectView
urlpatterns = patterns('myproject.prelude.views',
# Home:
url(r'^$', 'home', name='home'),
#login
url(r'^login/$', 'login', name='login'),
url(r'^welcome/$', 'welcome', name='welcome'),
# Registration Portal
# Registration Portal
url(r'^uportal/$', 'uportal', name='uportal'),
url(r'^uportal/ugreg/find/$', 'findmember', name='findmember'),
url(r'^uportal/ugreg/search/$', 'searchmember', name='searchmember'),
url(r'^uportal/ugreg/$', 'ugreg', name='ugreg'),
url(r'^uportal/ugreg/initiate-payment/$', 'initiatepayment', name='initiatepayment'),
url(r'^uportal/ugreg/verifypayment/$', 'verifypayment', name='verifypayment'),
url(r'^uportal/ugreg/proceedpayment/$', RedirectView.as_view(url='https://bestng.com/pay'), name='remote_admin'),
url(r'^uportal/ugreg/completepayment/$', completepayment, name='completepayment'),
Thank you
It appears that your problem is that request is an str object rather than a request object.
Please produce urls.py and views.py.
For readability, let’s rewrite the part below:
url = 'https://bestng.com/api/v1/gettransaction.json'
params = '?productid={product_id}&transactionreference={nid}&amount={famt}'
raw = urllib.urlopen(url + params.format(**locals()))
Or even, like so:
url = 'https://bestng.com/api/v1/gettransaction.json'
params = '?productid={product_id}&transactionreference={nid}&amount={famt}'
request = url + params.format(**locals())
raw = urllib.urlopen(request)
Also, the try block is not what I would use. Instead, I would use the get method of the POST dict and return a flag value:
nid = request.POST.get('tnxref', False)
I am unable to reproduce the error you are getting. With a slightly different project-level urls.py (very simplified), the ‘completepayment’ view works fine for me. Here is urls.py.
from django.conf.urls import patterns, url
from app.views import completepayment
# The app is simply called app in my example.
urlpatterns = patterns('',
# I remove the prefix
url(r'^uportal/ugreg/completepayment/$', completepayment, name='completepayment'),
)
# This last parenthesis might be missing in your code.
Related
When I transfer to the test url, an error pops up:
Reverse for 'movie' not found. 'movie' is not a valid view function or pattern name.
Here is my self test:
class BooksApiTestCase(APITestCase):
def setUp(self):
self.movie_1 = Movie.objects.create(title="terminator", year="1990", rating="5",url="retminator")
self.movie_2 = Movie.objects.create(title="robocop", year="1991", rating="4",url="robocop")
self.movie_3 = Movie.objects.create(title="rembo", year="1992", rating="3",url='rembo')
def test_get(self):
url = reverse('movie')
print(url)
response = self.client.get(url)
serializer_data = MovieListSerializer([self.movie_1, self.movie_2, self.movie_3], many=True).data
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual(serializer_data, response.data)
Here is my self url:
urlpatterns = format_suffix_patterns([
path("movie/", views.MovieViewSet.as_view({'get': 'list'})),
Hi #Andrew and Welcome to StackOverflow.
To use reverse() you have to properly set the view's name in the urlpatterns
urlpatterns = format_suffix_patterns([
path("movie/", views.MovieViewSet.as_view({'get': 'list'}, name='movie')
]),
Refer to the official documentation
I have this error when try to open a path. It requires a pk in my def and i inserted it, but still the issue is there. If someone could help, i would owe you a lot!
This is the error i have in browser:
TypeError at /batches/
index() missing 1 required positional argument: 'pk'
Request Method: GET
Request URL: http://127.0.0.1:8000/batches/
Django Version: 1.11.1
Exception Type: TypeError
Exception Value:
index() missing 1 required positional argument: 'pk'
Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 185
Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
Python Version: 3.6.1
Python Path:
['/Users/cohen/Documents/project/sanctions',
'/Users/cohen/Documents/project/sanctions',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyObjC']
Server time: Mon, 24 Jul 2017 10:47:02 +0000
My urls in batches
from django.conf.urls import url
from . import views
urlpatterns = [
# /batches/
url(r'^$', views.index, name='index'),
# /batches/2
url(r'^(?P<batches_id>[0-9]+)/$',views.detail, name="detail"),
# businessname/1
url(r'^(?P<businessname_id>[0-9]+)/$',views.index_businessname, name="detail_businessname"),
# individuals/1
url(r'^(?P<individuals_id>[0-9]+)/$', views.index_individuals, name="detail_individuals"),
]
And the views:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import BusinessName
from .models import Individuals
from .models import Batches
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request, pk):
all_Batches = Batches.objects.all()
html = ''
for batch in all_Batches:
url = '/batches/' + str(batch.id) + '/'
html += '' + str(batch.BatchNumber)+ '<br>'
return HttpResponse(html)
def detail(request, batch_id):
return HttpResponse("<h2>Details for Batches ID:" + str(batch_id) + "</h2")
def index_businessname(request):
all_BusinessNames = BusinessName.objects.all()
html = ''
for bn in all_BusinessNames:
url = '/businessname/' + str(bn.id) + '/'
html += '' + bn.FullName + '<br>'
return HttpResponse(html)
def detail_businessnames(request, bn_id):
return HttpResponse("<h2>Details for Business Names ID:" + str(bn_id) + "</h2")
def index_individuals(request):
all_individuals = Individuals.objects.all()
html = ''
for i in all_individuals:
url = '/individuals/' + str(i.id) + '/'
html += '' + i.FullName + '<br>'
return HttpResponse(html)
def detail_individuals(request, i_id):
return HttpResponse("<h2>Details for Individual Names ID:" + str(i_id)+ "</h2")
Thank you in advance,
Cohen
Include pk in your url.
Change your url like this,
url(r'(?P<pk>\d+)/$', views.index, name='index'),
instead of,
# /batches/
url(r'^$', views.index, name='index'),
OR,
if you are not passing pk to views then remove pk from index view as showned below.
def index(request):
all_Batches = Batches.objects.all()
html = ''
for batch in all_Batches:
url = '/batches/' + str(batch.id) + '/'
html += '' + str(batch.BatchNumber)+ '<br>'
return HttpResponse(html)
There are two arguments for the index view. The URL that you have written only gives request. You must give pk as an input just like the detail URL
Your url /batches/ has no parameter. So,
Your index view should be
def index(request):
# ......
I am working on a cartridge project. I have created custom html templates for better visual and now I want to render all data which is coming through cartridge's built in APIs on my custom html pages. For.ex. I have a product.html, on which I want to show all products stored in db (category wise).
Actually, I tried to explore url,
url("^shop/", include("cartridge.shop.urls")),
I am not getting that on which API or Function, this url is hitting.
urls.py file of shop app looks like this, I tested it, none of those url get called,
from __future__ import unicode_literals
from django.conf.urls import url
from mezzanine.conf import settings
from cartridge.shop import views
_slash = "/" if settings.APPEND_SLASH else ""
urlpatterns = [
url("^product/(?P<slug>.*)%s$" % _slash, views.product,
name="shop_product"),
url("^wishlist%s$" % _slash, views.wishlist, name="shop_wishlist"),
url("^cart%s$" % _slash, views.cart, name="shop_cart"),
url("^checkout%s$" % _slash, views.checkout_steps, name="shop_checkout"),
url("^checkout/complete%s$" % _slash, views.complete,
name="shop_complete"),
url("^invoice/(?P<order_id>\d+)%s$" % _slash, views.invoice,
name="shop_invoice"),
url("^invoice/(?P<order_id>\d+)/resend%s$" % _slash,
views.invoice_resend_email, name="shop_invoice_resend"),
]
These are cartridge's views for '/shop/product', '/shop/wishlist' and '/shop/cart'
from __future__ import unicode_literals
from future.builtins import int, str
from json import dumps
from django.contrib.auth.decorators import login_required
from django.contrib.messages import info
from django.core.urlresolvers import reverse
from django.db.models import Sum
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.template.loader import get_template
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from mezzanine.conf import settings
from mezzanine.utils.importing import import_dotted_path
from mezzanine.utils.views import set_cookie, paginate
from mezzanine.utils.urls import next_url
from cartridge.shop import checkout
from cartridge.shop.forms import (AddProductForm, CartItemFormSet,
DiscountForm, OrderForm)
from cartridge.shop.models import Product, ProductVariation, Order
from cartridge.shop.models import DiscountCode
from cartridge.shop.utils import recalculate_cart, sign
try:
from xhtml2pdf import pisa
except (ImportError, SyntaxError):
pisa = None
HAS_PDF = pisa is not None
# Set up checkout handlers.
handler = lambda s: import_dotted_path(s) if s else lambda *args: None
billship_handler = handler(settings.SHOP_HANDLER_BILLING_SHIPPING)
tax_handler = handler(settings.SHOP_HANDLER_TAX)
payment_handler = handler(settings.SHOP_HANDLER_PAYMENT)
order_handler = handler(settings.SHOP_HANDLER_ORDER)
def product(request, slug, template="shop/product.html",
form_class=AddProductForm, extra_context=None):
"""
Display a product - convert the product variations to JSON as well as
handling adding the product to either the cart or the wishlist.
"""
published_products = Product.objects.published(for_user=request.user)
product = get_object_or_404(published_products, slug=slug)
fields = [f.name for f in ProductVariation.option_fields()]
variations = product.variations.all()
variations_json = dumps([dict([(f, getattr(v, f))
for f in fields + ["sku", "image_id"]]) for v in variations])
to_cart = (request.method == "POST" and
request.POST.get("add_wishlist") is None)
initial_data = {}
if variations:
initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
initial_data["quantity"] = 1
add_product_form = form_class(request.POST or None, product=product,
initial=initial_data, to_cart=to_cart)
if request.method == "POST":
if add_product_form.is_valid():
if to_cart:
quantity = add_product_form.cleaned_data["quantity"]
request.cart.add_item(add_product_form.variation, quantity)
recalculate_cart(request)
info(request, _("Item added to cart"))
return redirect("shop_cart")
else:
skus = request.wishlist
sku = add_product_form.variation.sku
if sku not in skus:
skus.append(sku)
info(request, _("Item added to wishlist"))
response = redirect("shop_wishlist")
set_cookie(response, "wishlist", ",".join(skus))
return response
related = []
if settings.SHOP_USE_RELATED_PRODUCTS:
related = product.related_products.published(for_user=request.user)
context = {
"product": product,
"editable_obj": product,
"images": product.images.all(),
"variations": variations,
"variations_json": variations_json,
"has_available_variations": any([v.has_price() for v in variations]),
"related_products": related,
"add_product_form": add_product_form
}
context.update(extra_context or {})
templates = [u"shop/%s.html" % str(product.slug), template]
return TemplateResponse(request, templates, context)
#never_cache
def wishlist(request, template="shop/wishlist.html",
form_class=AddProductForm, extra_context=None):
"""
Display the wishlist and handle removing items from the wishlist and
adding them to the cart.
"""
if not settings.SHOP_USE_WISHLIST:
raise Http404
skus = request.wishlist
error = None
if request.method == "POST":
to_cart = request.POST.get("add_cart")
add_product_form = form_class(request.POST or None,
to_cart=to_cart)
if to_cart:
if add_product_form.is_valid():
request.cart.add_item(add_product_form.variation, 1)
recalculate_cart(request)
message = _("Item added to cart")
url = "shop_cart"
else:
error = list(add_product_form.errors.values())[0]
else:
message = _("Item removed from wishlist")
url = "shop_wishlist"
sku = request.POST.get("sku")
if sku in skus:
skus.remove(sku)
if not error:
info(request, message)
response = redirect(url)
set_cookie(response, "wishlist", ",".join(skus))
return response
# Remove skus from the cookie that no longer exist.
published_products = Product.objects.published(for_user=request.user)
f = {"product__in": published_products, "sku__in": skus}
wishlist = ProductVariation.objects.filter(**f).select_related("product")
wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
context = {"wishlist_items": wishlist, "error": error}
context.update(extra_context or {})
response = TemplateResponse(request, template, context)
if len(wishlist) < len(skus):
skus = [variation.sku for variation in wishlist]
set_cookie(response, "wishlist", ",".join(skus))
return response
#never_cache
def cart(request, template="shop/cart.html",
cart_formset_class=CartItemFormSet,
discount_form_class=DiscountForm,
extra_context=None):
"""
Display cart and handle removing items from the cart.
"""
cart_formset = cart_formset_class(instance=request.cart)
discount_form = discount_form_class(request, request.POST or None)
if request.method == "POST":
valid = True
if request.POST.get("update_cart"):
valid = request.cart.has_items()
if not valid:
# Session timed out.
info(request, _("Your cart has expired"))
else:
cart_formset = cart_formset_class(request.POST,
instance=request.cart)
valid = cart_formset.is_valid()
if valid:
cart_formset.save()
recalculate_cart(request)
info(request, _("Cart updated"))
else:
# Reset the cart formset so that the cart
# always indicates the correct quantities.
# The user is shown their invalid quantity
# via the error message, which we need to
# copy over to the new formset here.
errors = cart_formset._errors
cart_formset = cart_formset_class(instance=request.cart)
cart_formset._errors = errors
else:
valid = discount_form.is_valid()
if valid:
discount_form.set_discount()
# Potentially need to set shipping if a discount code
# was previously entered with free shipping, and then
# another was entered (replacing the old) without
# free shipping, *and* the user has already progressed
# to the final checkout step, which they'd go straight
# to when returning to checkout, bypassing billing and
# shipping details step where shipping is normally set.
recalculate_cart(request)
if valid:
return redirect("shop_cart")
context = {"cart_formset": cart_formset}
context.update(extra_context or {})
settings.use_editable()
if (settings.SHOP_DISCOUNT_FIELD_IN_CART and
DiscountCode.objects.active().exists()):
context["discount_form"] = discount_form
return TemplateResponse(request, template, context)
When you hit shop url, your application will try to use an empty url from your cartridge.shop.urls file. So basically when you would like to check which API / view is called, go to this file and look for something similar to this:
url(r'^$', 'your-view', name='your-view'),
ok after posting your second urls file you have following options:
you call:
/shop/wishlist/ - you are executing a view named wishlist
/shop/cart/ - you are executing a view named cart
/shop/checkout/complete/ - you are executing a view named complete
so just find your views.py file, and all those views are going to be there
I am trying to overwrite ROOT_URLCONF with another url when the request contains "api" subdomain and this is what I have so far.
from django.utils.cache import patch_vary_headers
class SubdomainMiddleware:
def process_request(self, request):
path = request.get_full_path()
root_url = path.split('/')[1]
domain_parts = request.get_host().split('.')
if (len(domain_parts) > 2):
subdomain = domain_parts[0]
if (subdomain.lower() == 'www'):
subdomain = None
else:
subdomain = None
request.subdomain = subdomain
request.domain = domain
if request.subdomain == "api":
request.urlconf = "rest_api_example.urls.api"
else:
request.urlconf = "rest_api_example.urls.
I tried using set_urlconf module "from django.core.urlresolvers" too but it didn't work. Am I missing something here?
Interestingly, I used set_urlconf module and request.urlconf to set url path and now it's working!
from django.core.urlresolvers import set_urlconf
if request.subdomain == "api":
set_urlconf("rest_api_example.urls.api")
request.urlconf = "rest_api_example.urls.api"
else:
set_urlconf("rest_api_example.urls.default")
request.urlconf = "rest_api_example.urls.default"
As for many things in django, there is already the app for that - https://github.com/jezdez/django-hosts
I have lots of simple Django views that look like this:
#team_leader_required
def view_all_teams(request):
teams = Team.objects.all()
template_vars = {'toolbar': 'teams',
'teams': teams}
return render(request, "all_teams.html", template_vars)
I end up writing lots of unit tests of the form:
def test_view_all_teams_renders(self):
user = self.create_team_leader()
self.log_in(user)
response = self.client.get(reverse('all_teams'))
self.assertHttp200(response)
Despite my convenience methods for creating users (e.g. .create_team_leader) and various convenience assertions (e.g. .assertHttp200), I still end up with a lot of duplication in my tests.
(My tests are simple since I can't see anything else useful to assert about these views -- TestCase.assertTemplateUsed breaks if you rename templates, even if the view is correct.)
It's easy to miss a test, which gives me little confidence when I rename templates. Is there any way I can automatically generate test cases? Something like (psuedo-code):
for every view in urls:
if view doesn't take extra arguments:
test that view returns 200 when a logged in superuser does a GET
EDIT
Here's a representative snippet from my urls.py:
urlpatterns = patterns('',
url(r'^teams/$', 'teams.views.view_all_teams', name='all_teams'),
url(r'^teams/major/$', 'teams.views.view_major_teams', name='major_teams'),
url(r'^teams/minor/$', 'teams.views.view_minor_teams', name='minor_teams'),
url(r'^teams/(?P<team_id>\d+)/$', 'teams.views.view_team', name='view_team'),
url(r'^teams/(?P<team_id>\d+)/edit$', 'teams.views.edit_team', name='edit_team'),
url(r'^teams/(?P<team_id>\d+)/delete$', 'teams.views.delete_team', name='delete_team'),
I'd like to automatically test the first three views in this list.
from django.core import urlresolvers
from django.test import TestCase
class SimpleTest(TestCase):
def test_simple_views(self):
url_names = [
'all_teams',
'major_teams',
'minor_teams',
'view_team',
'edit_team',
]
user = self.create_team_leader()
self.log_in(user)
for url_name in url_names:
try:
url = urlresolvers.reverse(url_name, args=(), kwargs={})
except urlresolvers.NoReverseMatch:
#print('Pass {}'.format(url_name))
continue
#print('Try {}'.format(url_name))
response = self.client.get(url)
self.assertHttp200(response)
If all url patterns have their name, You can use follow code to define url_names:
url_names = [p.name for p in teams.urls.urlpatterns]
Known Issues
If view function fail, you will not know which view failed.
Views next to failed view will not be tested.
Another version that handle above issues.
import unittest
from django.core import urlresolvers
from django.test import TestCase
from teams.urls import urlpatterns
class SimpleTest(TestCase):
...
def setUp(self):
user = self.create_team_leader()
self.log_in(user)
url_names = [p.name for p in urlpatterns]
vs = vars()
def make_test_function(idx, url_name, url):
def t(self):
response = self.client.get(url)
self.assertHttp200(response)
t.__name__ = 'test_' + idx
t.__doc__ = 'simple get test for ' + url_name
return t
for i, url_name in enumerate(url_names):
i = str(i)
try:
url = urlresolvers.reverse(url_name, args=(), kwargs={})
vs['test_' + i] = make_test_function(i, url_name, url)
except urlresolvers.NoReverseMatch as e:
vs['test_' + i] = unittest.skip(url_name + ' requires parameter(s) or view not found')(lambda: 0)
del url_names, vs, make_test_function,