Django Error ---index() missing 1 required positional argument: 'pk' - python

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):
# ......

Related

No Reverse Match Found error in Django when using < > in URL

I'm having problems with my URL paths.
Whenever I remove -- path('<query>/follow', views.follow, name='follow') -- everything works fine. When I include it, the page with the link on it reveals 'Reverse for 'follow' with no arguments not found' though I can manually type the follow path into the URL and it succeeds. Why is this and how can I fix it?
html
Follow
urls.py
urlpatterns = [
path('', views.explore, name='explore'),
path('happening/profile/', views.profile, name='profile'),
path('happening/', views.happening, name='happening'),
path('home/', views.home, name='home'),
path('home/likes/', views.likes, name='likes'),
path('<query>/follow', views.follow, name='follow'),
path('<query>/', views.profpage, name='profpage'),
]
views.py
def profpage(request, query):
obj = User.objects.filter(username=query)
if not obj:
attempt = {'user':query}
return render(request, 'error.html', attempt)
try:
obj2 = reversed(get_list_or_404(Comments, user=query))
except:
obj2= {}
try:
obj3 = get_list_or_404(Comments, user=query)
except:
obj3 = {}
like_dict={}
for x in obj3:
likes = x.likes.all().count()
like_dict[int(x.id)] = int(likes)
img = UserProfile.objects.filter(user__username=query)
for x in obj:
obj = x
for x in img:
img=x
content = {'obj': obj,
'img':img,
'info':obj2,
'like_dict':like_dict,
'query':query,
}
return render(request, 'profpage.html', content)
def follow(request, query):
print("WORKING")
return HttpResponse(request)

Django: HTTP error 410 (Gone) with RedirectView

I get an HTTP 410 error when invoking the following Django View:
>>> views.py:
class ReopenMilestoneView(
dj_auth_mixins.LoginRequiredMixin, dj_views.RedirectView
):
pattern_name = 'bibliotheka_dashboard'
def dispatch(self, request, *args, **kwargs):
print('DISPATCH BEGIN')
instance = project_models.Milestone.objects.get(pk=kwargs['pk'])
instance.state = project_models.STATE_OPEN
instance.save()
print('DISPATCH END')
return super(ReopenMilestoneView, self).dispatch(
request, *args, **kwargs
)
def http_method_not_allowed(self, *args, **kwargs):
print('HTTP NOT ALLOWED BEGIN')
try:
return super(ReopenMilestoneView, self).http_method_not_allowed(
*args, **kwargs
)
except:
print('EXCEPTION')
print('HTTP NOT ALLOWED END')
def get_redirect_url(self, *args, **kwargs):
print('REDIRECT BEGIN')
result = super(ReopenMilestoneView, self).get_redirect_url(
*args, **kwargs
)
print('REDIRECT END, result = ' + str(result))
url = urlresolvers.reverse('bibliotheka_dashboard')
url2 = urlresolvers.reverse(self.pattern_name)
print('REDIRECT END, URL_resolved = ' + str(url))
print('REDIRECT END, pattern_name = ' + str(self.pattern_name))
print('REDIRECT END, URL_2_resolved = ' + str(url2))
return result
>>> urls.py:
...
url(
r'^milestone/dashboard/$',
project_views.MilestoneDashboard.as_view(),
name='milestone_dashboard'
),
url(
r'^milestone/(?P<pk>[\w-]+)/dashboard/$',
project_views.MilestoneDashboard.as_view(),
name='milestone_specific_dashboard'
),
...
I added prints through the three methods form "RedirectView" that are mentioned in the Django documentation as part of the regular workflow (django).
Dispatch is properly executed but, when resolving automatically the "pattern_name", "RedirectView" fails... manually resolving it, solves the problem.
DISPATCH BEGIN
DISPATCH END
REDIRECT BEGIN
REDIRECT END, result = None
REDIRECT END, URL_resolved = /
REDIRECT END, pattern_name = bibliotheka_dashboard
REDIRECT END, URL_2_resolved = /
Gone: /prj/milestone/2/reopen/
[12/Jul/2017 13:28:34] "GET /prj/milestone/2/reopen/ HTTP/1.1" 410 0
I have used "RedirectView" before but I have never got this error, any ideas? Django is not returning a lot of info back...
My URLs are defined as follows:
from django.conf.urls import url, include
from django.conf.urls import static as dj_static
from django.contrib import admin
from bibliotheka import settings as bibliotheka_settings
from documentation.views import project as project_views
urlpatterns = [
url(
r'^$',
project_views.MilestoneDashboard.as_view(),
name='bibliotheka_dashboard'
),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^accounts/', include('allauth.urls')),
url(r'^prj/', include('documentation.urls.project')),
url(r'^dox/', include('documentation.urls.documents')),
url(r'^dox/', include('documentation.urls.discrepancies')),
]
if bibliotheka_settings.DEBUG:
urlpatterns += dj_static.static(
bibliotheka_settings.MEDIA_URL,
document_root=bibliotheka_settings.MEDIA_ROOT
)
I am trying to redirect to "/" with the problematic views.
Django is failing to reverse milestone_dashboard. In Django <= 1.11, it silences the NoReverseMatch, and returns a 410 response.
This behaviour has been changed in Django 2.0 (see ticket 26911), so Django will no longer silence the exception.
When you use pattern_name, Django tries to reverse with the same args and kwargs. You do not want this, as you are redirecting from a url containing the pk to a url that does not have any arguments.
You can set url with reverse_lazy:
from django.urls import reverse_lazy
class ReopenMilestoneView(RedirectView):
url = reverse_lazy('bibliotheka_dashboard')

How to render output of cartridge API's on custom HTML page?

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

Unable to retrieve HTTP Post data from external API in django

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.

SyntaxError in Django

I am trying to follow the django tutorial, (chapter 4, http://www.djangobook.com/en/2.0/chapter04.html). But the code further below throws a syntax error.
error:
Request Method: GET
Request URL: http://127.0.0.1:1222/hello/
Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, line 23)
Exception Location: /home/milad/djangobook/djangobook/urls.py in <module>, line 2
urls.py
from django.conf.urls import patterns, include, url
from djangobook.views import hello, showtime, plustime
urlpatterns = patterns('',('^hello/$',hello),('^time/$',showtime),(r'^time/plus/(\d{1,2})/$',plustime),
)
views.py
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
import datetime
def hello(request):
return HttpResponse ("Hello Dear Django!")
def showtime(request):
now = datetime.datetime.now()
t = get_template('showtime.html')
html = t.render(Context({'time':now}))
return HttpResponse(html)
def plustime(request,plus):
try:
plus = int(plus)
except ValueError:
raise Http404()
now = datetime.datetime.now() + datetime.timedelta(hours=plus)
t = get_template('plustime.html')
html = t.render(Context({'plus1':now})
return HttpResponse(html)
You are missing a closing parenthesis on the preceding line:
html = t.render(Context({'plus1':now})
# --- 1 --2 -- 2 but no 1
add ) at the end there:
html = t.render(Context({'plus1':now}))

Categories