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

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)

Related

Django redirect not working in my view function

From my crop crop_prediction view I am trying to redirect it to 'http://localhost:8000/Efarma/crop_detail/' page but instead of this it render the current html page ,the home page which is also the starting page of this website.
Some error is showing in my console '[26/Apr/2022 22:31:29,457] - Broken pipe from ('127.0.0.1', 62868)' but I have no idea what is it.
To go to crop_detail page i have to manually put it in search box.
urls.py:-
from django.urls import path, include
from .import views
urlpatterns = [
path('', views.home),
path('crop_prediction/', views.crop_prediction),
path('crop_detail/', views.crop_info)
]
views.py:-
def home(request):
return render(request, 'Efarma/index.html')
def crop_prediction(request):
global resultJson, firebase
print(request.POST)
print(request.GET)
if request.method == "POST":
N = float(request.POST.get("nitrogen"))
P = float(request.POST.get("phosphorus"))
K = float(request.POST.get("potassium"))
ph = float(request.POST.get("ph"))
rainfall = float(request.POST.get("rainfall"))
city = request.POST.get("city")
if weather_fetch(city) != None:
temperature, humidity = weather_fetch(city)
data = np.array([[N, P, K, temperature, humidity, ph, rainfall]])
print(temperature, humidity, "--------kkk-------")
my_prediction = pickle.load(
open('CropRecommendation\model\model.pkl', 'rb'))
final_prediction = my_prediction.predict(data)
value = final_prediction[0]
firebase = firebase.FirebaseApplication(
'https://e-farma-5dc42-default-rtdb.firebaseio.com/')
predicted_crop_info = firebase.get(value, None)
predicted_crop_info["crop"] = value
resultJson = dumps(predicted_crop_info)
return redirect('http://localhost:8000/Efarma/crop_detail/')
else:
return redirect('http://localhost:8000/Efarma/crop_detail/')
def crop_info(request):
print(resultJson)
return render(request, "Efarma/crop_detail.html", {"result": resultJson})
error:-

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

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

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

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.

Django attribute error. 'module' object has no attribute 'XYZ'

So this is in my urls.py
from django.conf.urls import patterns, include, url
from v1_1 import views
urlpatterns = patterns('',
url(r'', include('social_auth.urls')),
url(r'^$', views.fblogin), ### LINE1
url(r'^logged-in/$', 'v1_1.views.fb_loggedin'), ### LINE2
)
And it results in error because of LINE1. It (the same code) used to work some time back. If i change LINE1 to url(r'^$', 'v1_1.views.fblogin'), it works fine... i am unable to understand the problem :/
Here's my views.py
from django.http import HttpResponse
from django.template import RequestContext, Context, Template
from django.template.loader import get_template
from kb_db1.models import User
from django.core.exceptions import ObjectDoesNotExist
import datetime
def home(request):
t = get_template('profile.html')
c = get_user(1)
r = t.render(c)
return HttpResponse(r)
def fblogin(request):
t = get_template('login.html')
c = Context({'name':'Suneet' , 'STATIC_URL':'/stic' , })
r = t.render(c)
return HttpResponse(r)
def fb_loggedin(request):
t = get_template('profile.html')
user = request.user
c = get_user(user)
#c = Context({'user2':user , 'fb_app_id':'139460226147895', 'app_scope':'email', 'STATIC_URL':'/stic' , })
r = t.render(c)
return HttpResponse(r)
def notfound(request):
t = get_template('404.html')
c = Context({'name': 'Adrian', 'section.title': 'Suneet'})
r = t.render(c)
return HttpResponse(r)
def display_meta(request):
t = get_template('done.html')
c = get_user(2)
#return render(request, t, {'m_list': m_list})
r = t.render(c)
return HttpResponse(r)
def get_user(user):
id = user.id
try:
u_list = User.objects.get(id=id)
try:
u_list.profile = u_list.get_profile()
u_list.profile = prettify_user(u_list.profile)
except ObjectDoesNotExist:
u_list.profile = u_list
u_list.profile.cumulative_rating = '- '
c = Context({'u_list':u_list, 'user2':user, 'STATIC_URL':'/stic'})
except ObjectDoesNotExist:
print("Either the entry or blog doesn't exist.")
c = Context({ 'name': 'Error', 'user2':user, 'fb_app_id':'139460226147895', 'STATIC_URL':'/stic'})
return c
def prettify_user(user):
try:
confident_rating, confident_votes = calc_rating(user.cumulative_rating, user.cumulative_votes, 5.2, 5)
user.cumulative_rating = "%.0f" %(confident_rating*10) # 9.750 => 97.50 => 98 | 9.749 => 97.49 => 97.4
user.cumulative_votes = confident_votes
except ObjectDoesNotExist:
user = 'me'
return user
def calc_rating(rating, votes, fake_rating_val, fake_votes_no):
total_votes = votes+fake_votes_no
rating = (float(rating*votes) + fake_rating_val*fake_votes_no)/total_votes
return rating, total_votes
def chck_anon(user):
if not user.is_anonymous:
user.is_anonymous = True
return user

Categories