I am trying to set up web app. I am having issues with passing host_id to template .html file
i get:
Reverse for 'about_abc' with arguments '('',)' not found. 1 pattern(s) tried: ['itpassed\\/(?P<host_id>[0-9]+)\\/about\\/$']
inter.html
<li>about</li>
When i use "1" instead of "host_id" its working, but it can't stay hardcoded like this.
views.py
from django.shortcuts import render
import warnings
import requests
import json
from django.http import HttpResponse
from django.template import loader
from .models import Host
[...]
def inter(request, host_id):
return render(request, 'itpassed/inter.html')
def about_abc(request, host_id):
response = requests.get(
'abc.net:1768/abc/api/v1/about',
verify='/cert/cacerts.pem',
headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'},
)
return HttpResponse(response.content)
urls.py
from django.urls import path
from .models import Host
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:host_id>/', views.inter, name='inter'),
path('<int:host_id>/about/', views.about_abc, name='about_abc'),
]
How to fix this? As far as i can see views.py should pass host_id to template.
Why hardcoded "1" works but, host_id don't?
thanks
def inter(request, host_id):
return render(request, 'itpassed/inter.html')
You are not passing anything to the inter.html template here - so the host_id template variable won't hold any value.
I believe you want this instead:
def inter(request, host_id):
return render(request, 'itpassed/inter.html', {"host_id": host_id})
Related
I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so:
http://10.58.1.157:8000/product/sandwich?product_id=1
Below are my codes for urls.py and views.py
So far, I have tried:
urls.py
from django.urls import path
from .views import ProductView
urlpatterns = [
path('sandwich/int:<product_id>/', ProductView.as_view()),
]
and:
urls.py
path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view())
views.py
import json
import bcrypt
import jwt
from django.views import View
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from .models import Product, Category, SubCategory
class ProductView(View):
def get(self, request):
product_id = request.GET.get('product_id', None)
return JsonResponse({'product_name':Product.objects.get(id=product_id).values()})
To clarify the GET request, I will add the screenshot of Postman below:
It seems like this is due to malformed URL path. That's whats typically indicative of 404-NotFound error.
You need to add question mark that essentially forms the querystring. It is processed and available as a dictionary-like object (a QueryDict) in request.GET in views.py
You can define it like so, with a ? using a REGEX pattern (You may also alter to your needs)
path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view()),
In your views.py you can filter them with
product_id = request.GET.get('product_id', None)
This should now hopefully return a response now that the URL cannot give a 404 error.
See this for an example
I finally solved the issue!
I looked at this page and improvised accordingly...
https://docs.djangoproject.com/en/3.0/topics/http/urls/#nested-arguments
the final version of request is:
http://127.0.0.1:8000/product/?product_id=1
and the urls.py is:
from django.urls import path, re_path
from .views import ProductView
urlpatterns = [
re_path(r'^(?:\?product_id=(?P<product_id>\d+)/)?$', ProductView.as_view()),
]
When I am executing the code,I get the following error
NoReverseMatch at /upload/
Reverse for 'compare' with keyword arguments '{u'uploaded_file_url2': '/media/SAMPLE1.xlsx', u'uploaded_file_url': '/media/SAMPLE.xlsx'}' not found. 1 pattern(s) tried: ['compare/']
myapp/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^upload/', views.upload,name='upload'),
url(r'^compare/(?P<uploaded_file_url>\w+)/(?P<uploaded_file_url2>\w+)$',views.compare,name='compare'),
]
views.py
from django.shortcuts import render,redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.conf.urls import url
from django.http import HttpResponseRedirect
from django.urls import reverse
def upload(request):
if request.method == 'POST':
myfile=request.FILES['myfile']
myfile2=request.FILES["myfile2"]
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
filename2=fs.save(myfile2.name, myfile2)
uploaded_file_url = fs.url(filename)
uploaded_file_url2 = fs.url(filename2)
return redirect(reverse('myapp:compare',kwargs={"uploaded_file_url":uploaded_file_url,"uploaded_file_url2":uploaded_file_url2 } ))
return render(request, 'myapp/upload.html')
def compare(request,uploaded_file_url,uploaded_file_url2):
a=uploaded_file_url
b=uploaded_file_url2
#some code here
return render(request,'myapp/compare.html',{"a":a,"b":b})
Here I want to pass uploaded_file_url and uploaded_file_url2 to compare
You're trying to pass all the data from the upload to the reverse function, so that it is part of the URL. But your "compare" URL does not expect any arguments at all.
Either change the URL so that it does expect arguments, or pass the uploaded filenames in the GET parameters or in the session.
In my urls.py I have set handler404 to CustomErrorView. CustomErrorView is a generic view which generates a template for an error based on the error message and error code that it receives.
Since the handler404 is only raised in the case of a 404 error, how can I send the errorcode = 404 kwarg to CustomErrorView whenever it is raised?
Already tried-
handler404 = CustomErrorView(errorcode = 404)
This causes an "Expected one positional argument, none given error."
handler404 = CustomErrorView(request, errorcode = 404)
This causes a NameError (Name 'request' is not defined)
My urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from blog_user.views import home, create_error_view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home),
url(r'^', include('user_manager.urls')),
]
handler404 = create_error_view(error = 404)
handler500 = create_error_view(error = 500)
My views.py (after using the modifications recommended by #knbk) :
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
def create_error_view(error = 404, mybad = False):
def custom_error_view(request, error, mybad):
''' Returns a generic error page. Not completed yet. error code and messages are supposed to be modular so that it can be used anywhere for any error in the page.'''
content = "Incorrect url"
context= {
'error': error,
'content':content,
'mybad':mybad
}
response = render(request, 'error.html', context=context, status=error)
return HttpResponse(response)
return custom_error_view
You can use a function closure to create the view function:
def create_error_view(error_code):
def custom_error_view(request, *args, **kwargs):
# You can access error_code here
return custom_error_view
Then just call create_error_view to set the handler:
handler404 = create_error_view(error_code=404)
Or you can use functools.partial(), which basically does the same:
from functools import partial
handler404 = partial(custom_error_view, error_code=404)
I am new to Django. I have to write a moke. My server will look at a specific address.
Like this:
portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999
I wrote:
urls.py
from django.conf.urls import patterns, url
from rt_moke import views
urlpatterns = patterns('',
url(r'code=(?P<code_id>\w+)/', views.Sapata, name='sapata'),
)
and views.py
from django.http import HttpResponse
status = {u"99999": u'{"code": "99999","status": "undelivered"}',\
u"88888": u'{"code": "88888","status": "delivered"}',\
}
def Sapata(request, code_id):
return HttpResponse(status[code_id])
When I request for portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999 without ? mark - it works, and with ?- not. I understand, that it is query string and Django skips it in the regexp. So what can I do?
This URL:
portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999
has two parts, the path:
portal/client_api.ashx
and the query string:
client=SAPRA&key=1234234&func=status&code=99999
which is parsed into request.GET.
In views.py you should get params from request (like simple dict in request.GET), for example:
def test(request):
code = request.GET.get('code') # here we try to get 'code' key, if not return None
...
and of course, we can't use GET params to parse URLs in urls.py. Your urls.py should looks like:
from django.conf.urls import patterns, url
from rt_moke import views
urlpatterns = patterns('',
url(r'^portal/client_api\.ashx$', views.Sapata, name='sapata'),
)
P.S. Please, don't use capital letters in names of functions.
I am new to Django coding....i want to show whatever is there in area_distnce.html...below is my code
Thanks in advance....
Distance.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
def area_distance(request):
return render_to_response('area_distance.html',locals(),context_instance=RequestContext(request))
urls.py
from django.conf.urls import patterns, include, url
from areas.Distance import area_distance
urlpatterns = patterns('',
url(r'^area/$','area_distance',name = 'area_distance'),)
When i run his it is giving
TypeError at /area/
'str' object is not callable
Looks like you have written view function area_distance() in Distance.py instead of views.py.
So you may want to update your urls.py to appropriately use that
url(r'^area/$', area_distance,name = 'area_distance'),)
---------------^ note no '...'
As you are doing from areas.Distance import area_distance this should work.
from django.http import HttpResponse
from django.template.context import RequestContext
def area_distance(request):
a= 1
b = a+1
t = get_template('area_distance.html')
c = RequestContext(request, locals())
return HttpResponse(t.render(c))
#url.py
from django.conf.urls import patterns, include, url
from areas.Distance import area_distance
urlpatterns = patterns('',
url(r'^area/$',area_distance,name = 'area_distance'),)
#template
{{ a }}
{{ b }}