How to consume url parameters in Django views - python-3.x

Getting an error always
The current path, <code>api/det/1</code>, didn’t match any of these.
My urls.py
url(r'^api/det/<int:id>',views.DetailsAPI.as_view(),name='DetailsAPI')
My views.py
class DetailsAPI(APIView):
def get(self,id):
filter_list=Details.objects.all()
#filter_list = Details.objects.get(id=id)
envid = self.kwargs['id']
df = read_frame(filter_list)
df_det = df.loc[df['Id'] == int(id)]
df_final=df_det.to_json(orient='records')
return HttpResponse(df_final, content_type = 'application/json')
I'm sure there is some simple stuff that i'm missing and i can't get it to work with whatever syntax i try.. Any suggestions?

Changing the url to the below one worked.
url(r'^api/det/(?P<id>\d+)',views.DetailsAPI.as_view(),name='DetailsAPI')

Related

how to execute the api call inside a django view only if the template coresspanding to this view is called

hi im trying to get access token for my application but i have a problem with executing an api call inside my "profile_token" django view
because i want to execut the call only if the template coresspanding to this view is called,
otherwise it keeps breaking the server because the user should first sign in to ebay then i can make this call
thank you for your help
here is a sample of the code
api = Connection(config_file='ebay.yaml', domain='api.sandbox.ebay.com', debug=True)
url_vars = {'SignIn&RuName': RuName, 'SessID': SessionID}
url = 'https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?'
constructed_url=(url + urllib.parse.urlencode(url_vars))
final_url=urllib.parse.unquote(constructed_url)
def profile(request):
context={
'final_url':final_url
}
return render(request,'users/profile.html',context)
request= {
'SessionID': SessionID
}
# i tried this
def profile_token(request):
response = api.execute('FetchToken', request)
return render(request, 'users/profile_token.html')
# and this
def profile_token(request):
if profile_token:
response = api.execute('FetchToken', request)
return render(request, 'users/profile_token.html')
i guess every time i post a question in here i find the answer by my self
so the mistake was the word 'request ' i should use 'r' or anything else other then 'request' because it is already reserved by the django view function
good luck
def profile(request):
RuName= 'driss_aitkassi-drissait-crm-SB-ijuzzy'
r= {
'RuName': RuName
}
response = api.execute('GetSessionID', r)
print(response)
res =response.text
tree= ET.fromstring(res)
for node in tree.iter('{urn:ebay:apis:eBLBaseComponents}GetSessionIDResponse'):
SessionID= node.find('{urn:ebay:apis:eBLBaseComponents}SessionID').text
print(SessionID)
url_vars = {'SignIn&RuName': RuName, 'SessID': SessionID}
url = 'https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?'
constructed_url=(url + urllib.parse.urlencode(url_vars))
final_url=urllib.parse.unquote(constructed_url)
print(final_url)
context={
'final_url':final_url
}
return render(request,'users/profile.html',context)

Error in django unittest: 'object has no attribute' object

I started testing views, but I found an error in the test, tell me where I went wrong, I'm just starting to learn, so don't judge strictly
my views:
`class MovieDetailView(Genre, DetailView):
model = Movie
slug_field = "url"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["star_form"] = RatingForm()
return context
`
my test looks like this:
`def test_starform_set_in_context(self):
request = RequestFactory().get('some-slug')
view = MovieDetailView()
view.setup(request)
context = view.get_context_data()
self.assertIn('star_form', context))`
url:
`path("<slug:slug>/", views.MovieDetailView.as_view(), name="movie_detail"),`
I think this is because Django's get_context_data() function uses the 'object' to pass it into the context.So, I suggest you to use get_object() method.
See this for more details: https://ccbv.co.uk/projects/Django/3.0/django.views.generic.detail/DetailView/
basically you need to return an object e.g.
def get_object(self,queryset=None):
obj = Movie.object.get(slug=self.kwargs.get('slug'))
return obj #also handle 404
or try one more thing :
slug_fields = slug
path should be
path("<str:slug>/", views.MovieDetailView.as_view(), name="movie_detail"),

django except matching query does not exist

I'm trying to use try and except in django; everything work perfect if the user exist but if the user doesn't exist instead of returning NULL; my function keep returning:
Userprofile matching query does not exist.
I know the user is not exist in table; I just want to not return anything instead of showing error page.
from django import template
from album.models import Album
from django.shortcuts import get_object_or_404, render
register = template.Library()
#register.inclusion_tag('album/user_album.html')
def userAlbumFunction(id):
try:
albums = Album.objects.filter(user_id = id)
except Album.DoesNotExist:
albums = None
return {'albums' : albums}
try:
albums = Album.objects.get(user_id = id)
except Album.DoesNotExist:
albums = None
pass

Adding query parameter for every flask GET request

Trying to figure out the right mechanism to use here.
I want to modify the flask request coming in every time.
I think the request is immutable, so I am trying to figure out if this mechanism exists.
Basically, I want to append a string onto the end of the request coming in.
I can hook into the request and the right time in a before_request handler like this:
#app.before_app_request
def before_request_custom():
# Get the request
req = flask.request
method = str(req.method)
if method == "GET":
# Do stuff here
pass
But I am not sure what to actually do to add this in, and don't see a way to accomplish it...I guess i could redirect, but that seems silly in this case. Any ideas?
The request object is immutable (https://werkzeug.palletsprojects.com/en/1.0.x/wrappers/#base-wrappers), but request.args or request.form can be set from ImmutableOrderedMultiDict to just OrderedMultiDict using Subclassing on Flask (https://flask.palletsprojects.com/en/1.1.x/patterns/subclassing/). Here's an example of how you could add that filter[is_deleted]=False URL param:
from flask import Flask, request, Request
from werkzeug.datastructures import OrderedMultiDict
class MyRequest(Request):
parameter_storage_class = OrderedMultiDict
class MyApp(Flask):
def __init__(self, import_name):
super(MyApp, self).__init__(import_name)
self.before_request(self.my_before_method)
def my_before_method(self):
if "endpoint" in request.base_url:
request.args["filter[is_deleted]"] = "False"
app = MyApp(__name__)
app.request_class = MyRequest
#app.route('/endpoint/')
def endpoint():
filter = request.args.get('filter[is_deleted]')
return filter
This way you can modify request.args before you actually send the request.
How about this?
from flask import g
#app.before_request
def before_request():
# Get the request
req = flask.request
method = str(req.method)
if method == "GET":
g.my_addon = "secret sauce"
return None
Then, g.my_addon is available in every view function:
from flask import g
#app.route('/my_view')
def my_view():
if g.my_addon == "secret sauce":
print('it worked!')
Using test_request_context() you can make the trick.
Related: https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data

pyramid transaction.manager doesn't update object

How can I update a row in DB using transaction.manager in Pyramid? Here is what I have:
DBSession:
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
View:
def create_update(request, post):
title = request.POST.get('title', None)
content = request.POST.get('content', None)
post.title = title
post.content = content
with transaction.manager:
if post.id is None:
DBSession.add(post)
transaction.commit()
This is how I get an existing post from DB:
def by_slug(slug):
return DBSession.query(BlogPost).filter(BlogPost.slug == slug).first()
where BlogPost is a sqlalchemy model.
When I create a new post, everything is fine, it is added and saved in DB, however, nothing happens when I edit an existing post. I've tried DBSession.flush(), result is the same - I can create a new post, but existing one is not updated. What am I missing?
Why your use transaction here?
The ZopeTransactionExtension on the DBSession in conjunction with the pyramid_tm being active on your project will handle all commits for you.
so just try this:
def create_update(request, post):
title = request.POST.get('title', None)
content = request.POST.get('content', None)
post.title = title
post.content = content
if post.id is None:
DBSession.add(post)
Apparently, the issue was, that I didn't have pyramid_tm under pyramid.includes in ini configuration:
[app:main]
use = egg:myproject
pyramid.includes =
pyramid_jinja2
pyramid_tm #this was missing
Weird, that I was not seeing any errors or anything, and it sort of worked, but was giving a lot of headaches.

Resources