Here I have Url
http://127.0.0.1:8000/accounts/google/login/callback/#access_token=ya29.a0AVA9y1tO4d94lkiHbIT2qjh89k0TNGXFMJ_6XzdHXvxLrsLbphuMaBmEvUHCSX8XWq5L3dqQ88ULG9Vsw1llmYi24DpbFamGcoW4KPZP-9y2ynPBJMqmuFdazz7t9KEp5qrdkVwvaCgYKATASAQASFQE65dr8nbFmeih28Lvt_Q68CBXhiQ0163
I want to get value of access_token and return that token as response mention below
but don't know the way to get query_parameter after hash(#)
{
"token":'ya29.a0AVA9y1tO4d94lkiHbIT2qjh89k0TNGXFMJ_6XzdHXvxLrsLbphuMaBmEvUHCSX8XWq5L3dqQ88ULG9Vsw1llmYi24DpbFamGcoW4KPZP-9y2ynPBJMqmuFdazz7t9KEp5qrdkVwvaCgYKATASAQASFQE65dr8nbFmeih28Lvt_Q68CBXhiQ0163'
}
in urls.py
from user.views import GoogleRedirect
path('accounts/google/login/callback/', GoogleRedirect.as_view())
in views.py
class GoogleRedirect(APIView):
def get(self, request):
return Response("success")
I don't know is this a good idea but if you really want to do this:
$.get(`{% url "grv" %}${window.location.hash.slice(1)}`, function(data, status){
console.log('done')
});
// be sure that URL has a slash at the end (grv)
urls.py
from user.views import GoogleRedirect
...
path('accounts/google/login/callback/<str:token>', GoogleRedirect.as_view(), name="grv")
...
views.py
class GoogleRedirect(APIView):
def get(self, request):
return JsonResponse({"token" : self.kwargs['token']})
Related
I am new in Django and I am bit confused in Django apiview for custom method.
In ApiView, How can I create a custom method and How to call from axios.
For example
Here is my View
class TimeSheetAPIView(APIView):
#action(methods=['get'], detail=False)
def getbytsdate(self, request):
return Response({"timesheet":"hello from getbydate"})
def get(self,request,pk=None):
if pk:
timesheet=get_object_or_404(TimeSheet.objects.all(),pk=pk)
serializer = TimeSheetSerializer(timesheet)
return Response({serializer.data})
timesheet=TimeSheet.objects.all()
serializer = TimeSheetSerializer(timesheet,many=True)
return Response({"timesheet":serializer.data})
Here is my URL=>
url(r'^timesheets_ts/(?P<pk>\d+)/$', TimeSheetAPIView.as_view()),
url(r'^timesheets_ts/', TimeSheetAPIView.as_view()),
Normally my url would be like=>
api/timesheet_ts/
this one will get all of my records.
So my question is how can I setup URL for getbytsdate or getbyname or other some kind of custom get method? and how can I call?
I tried like this way=>
url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', TimeSheetAPIView.as_view()),
and I called like that
api/timesheets_ts/getbytsdate/?tsdate='test'
Its not work.
So please can u explain for the custom method in apiview and url setting?
In addition to your implementation, you just need to show your custom get request to your urls.py. Edit your urls.py as follows:
# urls.py
timesheet_getbytsdate_detail = TimeSheetAPIView.as_view({'get': 'getbytsdate'})
timesheet_detail = TimeSheetAPIView.as_view({'get': 'retrieve'})
urlpatterns = [
url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', getbytsdate_detail),
url(r'^timesheets_ts/(?P<pk>[0-9]+)/', timesheet_detail),
]
EDIT: You need to use the combination viewsets.GenericViewSet and mixins.RetrieveModelMixin instead of APIVewto get use of that:
class TimeSheetAPIView(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
#action(methods=['get'], detail=False)
def getbytsdate(self, request):
return Response({"timesheet":"hello from getbydate"})
def retrieve(self, request, *args, **kwargs):
timesheet=self.get_object()
serializer = TimeSheetSerializer(timesheet)
return Response({serializer.data})
timesheet=TimeSheet.objects.all()
serializer = TimeSheetSerializer(timesheet,many=True)
return Response({"timesheet":serializer.data})
I am trying to use reverse method in django view but I got an exception 'str' object has no attribute 'get'.
here is my view
class AbandonTicketView(View):
context = dict()
template_name = "places/order_detail.html"
def get(self, request, uidb64, token, ordercode):
order = abandon_oder(uidb64, token, ordercode)
if order is not None and order.paid is False:
return reverse("order_detail", kwargs={"ordercode": order.code})
return redirect("tickets")
view that I want to go:
class OrderDetailView(LoginRequiredMixin, View):
template_name = "places/order_detail.html"
context = dict()
def get(self, request, ordercode):
order = Order.objects.get(code=ordercode)
self.context["order"] = order
self.context["key"] = settings.tycoon.STRIPE_PUBLISHABLE_KEY
if order.send_count >= 3 and order.paid is False:
self.context["abandon_ticket"] = "Order was canceled"
return render(request, template_name=self.template_name, context=self.context)
def post(self, request, ordercode):
order = pay_for_ticket(ordercode, request.POST["stripeToken"], request.user)
self.context["order"] = order
return render(request, template_name=self.template_name, context=self.context)
here is url:
path("orders/<code:ordercode>/detail/", views.OrderDetailView.as_view(), name="order_detail"),
path("tickets/", views.OrderedTicketsView.as_view(), name="tickets"),
I don't really know why it happends, because I do the similar reverse earlier and everything works fine, but not now. Could you help me please to solve this problem?
reverse() returns a string, but your view has to return a HttpResponse.
Change your line:
return reverse("order_detail", kwargs={"ordercode": order.code})
to also use redirect() (like the other part of your view)
return redirect("order_detail", args=[order.code, ])
or maybe even simplified like this
return redirect("order_detail", order.code)
Does that work?
You could use redirect with reverse and it works.
from django.shortcuts import redirect
return redirect(reverse("order_detail", kwargs={"ordercode": order.code}))
OR the second keyword to do the same thing is:
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse("order_detail", kwargs={"ordercode": order.code}))
The reasoning behind this is that reverse just returns the URL in the form of a string. When you want to redirect an HTTP Response should happen. Only cases where only the URL is required reverse should be used otherwise you need to generate an HTTP Response as well.
I'm using Django 2.0 and have been trying to redirect user to other view from get_context_data
my url pattern is
mainapp.urls
urlpatterns = [
path('learn/', include('learn.urls', namespace='learn')),
path('admin/', admin.site.urls),
]
app.url
app_name = 'learn'
urlpatterns = [
path('success/<course_learn_id>/<session>', LearnSuccess.as_view(), name='success'),
]
and LearnSuccess view
class LearnQuestion(FormView):
form_class = SessionForm
template_name = 'learn/learn_question.html'
def get_context_data(self, **kwargs):
context = super(LearnQuestion, self).get_context_data(**kwargs)
course_learn = CourseLearn.objects.get(pk=self.kwargs['course_learn_id'])
session = self.request.GET['session']
question, question_type, options, complete = CourseLearn.objects.get_next_question(course_learn, session)
if complete:
return redirect('learn:success', course_learn_id=course_learn.pk, session=session)
context['complete'] = complete
context['question'] = question
context['question_type'] = context_type
context['options'] = options
context['session'] = session
return context
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(self.__class__, self).dispatch(request, *args, **kwargs)
I'm using Ajax to render this view and want to redirect user when complete is True
But this is giving error as
TypeError: context must be a dict rather than HttpResponseRedirect.
I even tried return reverse() but it is also giving error.
Trying
return redirect('learn:success', kwargs={'course_learn_id':course_learn.pk, 'session':session})
gives error
django.urls.exceptions.NoReverseMatch: Reverse for 'success' with keyword arguments
'{'kwargs': {'course_learn_id': UUID('374ccfcd-37b5-40d3-8673-01ca111f42bc'), 'session': '1524972935'}}' not found.
1 pattern(s) tried: ['learn\\/success\\/(?P<course_learn_id>[^/]+)\\/(?P<session>[^/]+)$']
get_context_data() is supposed to be for you to add additional context to the template before it is rendered. It is not for doing other view-level logic.
You are trying to return a redirect response object from there, which is invalid - the return value of get_context_data() can only be a dictionary.
The logic you are currently trying to perform here should instead be in your view's get() method, something like:
def get(self, *args, **kwargs):
course_learn = CourseLearn.objects.get(pk=kwargs['course_learn_id'])
session = self.request.GET['session']
question, question_type, options, complete = CourseLearn.objects.get_next_question(course_learn, session)
if complete:
return redirect('learn:success', course_learn_id=course_learn.pk, session=session)
return super().get(*args, **kwargs)
Solved it by using render_to_response. For those who may need it, add a function inside the class
def render_to_response(self, context, **response_kwargs):
if context['complete']:
return redirect(reverse('learn:success',
kwargs={
'course_learn_id': context['course_learn'].pk,
'session': context['session']
}))
return super(LearnQuestion, self).render_to_response(context, **response_kwargs)
and from get_context_data() send the context data
if complete:
context['complete'] = complete
context['course_learn'] = course_learn
context['session'] = session
return context
I'm a noob, so please excuse me if this is a silly request. I am trying to create custom RSS feeds for each category of a website, but somehow I can't manage to pass the parameter (a category slug) in order to properly build the requested feed. The RSS should be located at an address like this: http://www.website.com/category-name/feed
Here's what I have:
In urls.py:
from project.feeds import FeedForCategory
urlpatterns = patterns('category.views',
#...
url(r'^(?P<category_slug>[a-zA-Z0-9\-]+)/feed/?$', FeedForCategory),
)
In feeds.py:
from django.contrib.syndication.feeds import Feed
class FeedForCategory(Feed):
def get_object(self, request, category_slug):
return get_object_or_404(Category, slug_name=category_slug)
def title(self, obj):
return "website.com - latest stuff"
def link(self, obj):
return "/articles/"
def description(self, obj):
return "The latest stuff from Website.com"
def get_absolute_url(self, obj):
return settings.SITE_ADDRESS + "/articles/%s/" % obj.slug_name
def items(self, obj):
return Article.objects.filter(category=category_slug)[:10]
The error that I get is: "_ init _() got an unexpected keyword argument 'category_slug'", but the traceback isn't helpful, it only shows some base python stuff.
Thank you.
From the doc: https://docs.djangoproject.com/en/dev/ref/contrib/syndication/
You need to pass an instance of the feed object to your url patterns. So do this in urls.py:
from project.feeds import FeedForCategory
urlpatterns = patterns('category.views',
#...
url(r'^(?P<category_slug>[a-zA-Z0-9\-]+)/feed/?$', FeedForCategory()),
)
views.py:
class ajax_profile():
def __init__(self, request):
username = request.REQUEST.get('username','')
email = request.REQUEST.get('email','')
password = request.REQUEST.get('password','')
action = request.REQUEST.get('action','')
options = {
'check_username' : self.check_username(username),
'check_email' : self.check_email(email),
'forgot_password' : self.forgot_password(email),
'login' : self.login(username, password),
}
options[action]
def check_username(self, username):
return HttpResponse('Test %s' % username)
def check_email(self, email):
pass
def forgot_password(self, email):
pass
def login(self, username, password):
pass
urls.py
(r'^ajax_profile/$', 'apps.profiles.views.ajax_profile'),
URL to call
ajax_profile/?action=check_username&username=testtest
ERROR: instance has no attribute 'status_code'
Why?
I don't recommend doing things this way. Your views should return HttpResponse objects, while ajax_profile's init method should initialize an instance of ajax_profile.
If you must, you can try having ajax_profile subclass HttpResponse, and use super to initialize the HttpResponse at the end of ajax_profile's __init__:
class ajax_profile(HttpResponse):
def __init__(self, request):
# ...
response_text = options[action]()
super(ajax_profile, self).__init__(response_text)
Also worth noting, the way options is set up, every method in the dictionary (check_username, check_email, etc) will be run every time regardless of the action. Probably not what you want.
your last line in init() should be return options[action]