I want to show progress bar in django template, on the basis of django post process/progress(form is ajax submit). is it possible? - ajax

def post(self, request, *args, **kwargs):
if attorney_data_list:
for i in len(attorney_data_list):
if(index%3 == 0):
process_percent = int(100 * float(index) / float(len(case_data_list)+1))
else:
pass
i want this process_percent value in django template on every for loop.is it possible?

No. Standard HTTP connections are request / response based, meaning that you only send the response to the browser once the function completely ran.
To provide the current process from within this function, you would probably need to use websockets, though I am not really familiar with them.
With standard HTTP-requests, you could use the database to store the process_percentage and use another ajax-request to retrieve the process_percentage from the database and send it to the browser.

Related

What is a safe way to allow REST APIs to be public?

In my website, people can see images given from REST APIs without login. I want to make some of my APIs not to require a user token. So, I had some research and I found the way below.
Since I need to use this way for production, I want to make sure if it is a safe way. The stores that will be given from the API have just store data such as name, urls, description, and images. Any of them are not related to any users.
Is it okay for me to use in production? Just so you know, I use Django REST Framework to serve data to frontend and use React js to show them in frontend side.
from rest_framework.decorators import authentication_classes, permission_classes
#authentication_classes([])
#permission_classes([])
class ListAllStores(APIView):
def get(self, request, format=None):
all_stores = Store.objects.all()
serializer = StoreSerializer(all_stores, many=True)
return Response(data=serializer.data)
You can try something link sending user type on header of each request.
And for the API without token send userType as anonymous or something like that
And for the API with token send userType as customer or something like that.
Create a method which will be called first thing from the each end points and validate the Request header.
If you want to make it more general you can map this end point and type of user as meta data setting, So next time if you have some '/image' end point which was allowed only to the customer user type but now you want it should be allowed to anon also so that can be easily done using that meta data file without changing the code.
You can be explicit by using AllowAny permission class, which will let public access to that endpoint.
from rest_framework import permissions, views
class ListAllStores(views.APIView):
permission_classes = (
permissions.AllowAny,
)
def get(self, request, format=None):
all_stores = Store.objects.all()
serializer = StoreSerializer(all_stores, many=True)
return Response(data=serializer.data)

How to send the authenticated response while authenticating a user via SAML in Rails?

I have been trying to implement SAML in my application, wherein I want to authenticate the user and create the SAML Token(response) and redirect the user to the other website wherein session gets created.
Till now I have been able to get info on init method and consume method, which will be implemented by the other website.
def init
request = OneLogin::RubySaml::Authrequest.new
redirect_to(request.create(saml_settings))
end
def consume
response = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
response.settings = saml_settings
if response.is_valid? && user = current_account.users.find_by_email(response.name_id)
authorize_success(user)
else
authorize_failure(user)
end
end
Following this Source.
I want to create the method which comes in between init and consume.
Updated:
Like I have this one which is I guess is following SAML 1.1, I wanted to know how can I generate a SAML 2.0 request using the get_settings method in Rails.
def SSOAccount.get_settings
settings = Onelogin::Saml::Settings.new
settings.issuer = "https://example.com/test"
settings.idp_sso_target_url ="https://testexample.com"
settings.idp_cert_fingerprint ="########"
settings.relying_party_identifier = "knsdfnsdf"
settings.assertion_consumer_service_url = "https://www.example.com/consume?http_referer=https://testexample.com"
settings.idp_confirmation_method = "urn:oasis:names:tc:SAML:1.0:cm:bearer"
settings.asserting_party_id = "23424dfsdf"
settings.referer_url = "https://textexample.com"
settings.groups = ["USER"]
settings
end
You can post the data, but do it in a way that resembles a redirect. The problem with a redirect being that the data is usually larger than can be accommodated in a browser acceptable url.
You need to do it this way so that the post comes from the user's browser rather than your server. That is, the post needs to take the user's browser session with it, so that the associated cookies and session data are submitted with the SAML token.
One solution is to use a self submitting form as shown within saml_tools_demo's indentifies#create view.
Have a look at the matching controller action to see how the data are constructed.

How to pass django error status to ajax

Using django rest framework with backbone.
Current situation:
Whenever an ajax call fails, django responds through get_error_response
As soon as get_error_response gets invoked, django raises a error on client side too, as i am not handling this error in django(server) side.
views.py snippet
def get_error_response(self):
return Response(
self.serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
Requirement:
I want to be able to pass all error statuses to $ajax.fail() promise, and handle it there on client side, thereby enabling me to show the error messages to user.
Note:something like the code given below is what i am expecting. But the problem is, this response would got to $ajax.done promise(), wheras i want it in $ajax.fail() promise
def get_error_response(self):
return Response({
"msg":self.serializer.errors, "error_status":status.HTTP_400_BAD_REQUEST
})
Do ask if more clarity is required.
No matter if you're using a Response from Django Rest Framework or the normal Django HttpResponse you always need to pass the keyworded argument status in order to make the response actually have the correct status code thus invoking the correct handler in your front end code.
What your last example does is only passing a data or content argument which is making the response class default to a 200 status code.
return Response(your_data, status=404)

Django: Is it possible create and send Json from a view to another server?

If i have a link like this one Get User Data who points in a view inside my own server, is there any way to send a json object (maybe just maybe with ajax?) to another external server and retrieve an answer? Something like this:
from django.shortcuts import render
def profile(request):
#send a json object to another server like http://www.myotherserver.com/user
#get the answer and process it
return render(request, 'accounts/profile.html' ,
{'profile_user': data_from_the_external_server})
The above i can implement it of course with jquery-ajax but i just was wondering if i can do it this way...
Thanks in advance.
Of course you can. Why wouldn't it be possible?
Don't code this in AJAX if that's not necessary.
There are 2 things you need, you need to prepare the JSon to send and then you need to send it to the API you want:
Look at "simplejson" to create the json data to send.
Look at "urllib" to send a request to another server in Python (like here: How to send a POST request using django?)
Also do not put it straight in your view. Create a new class for it. So in your view you'll have something like that:
def profile(request):
# instantiate your service here (better with DI)
profile_user = my_service.get_profile_user()
return render(
request,
'accounts/profile.html' ,
{
'profile_user': profile_user
}
)
If you need to send HTTP data (via a POST or GET) to another server and receive a result from within your view, you can use Python's urllib2 library. However there is an easier third party library called Requests which can handle this task for you.

django, return to previous page after form POST submit

In my web page I have a form that is being filled with data after some ajax requests. For example when a user chooses an item from the list, a simple ajax request is sent to the database that the item has been selected (but not confirmed, yet). Then the list on the web page reloads using a simpe ajax request (just the list, not the whole page) to fetch the new item list.
I think this is more or less a classic cart implementation.
However, when the user presses submit (classic form POST submit, not ajax POST for some reasons concerning the implementation) to confirm the whole list, I would like to return to the current page. (Current page varies) Is this possible? I am using django.
Thanks.
You can supply a next GET parameter when submitting the form, similar to django.contrib.auth's login() method:
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login:
<form action="/url/to/post/form/?next={{ some_variable }}">
where the variable can simply be the current URL (taken from the request) or a generated URL. In the view processing the form, simply check for a next parameter and redirect appropriately:
from django.shortcuts import redirect
if 'next' in request.GET:
return redirect(request.GET['next'])
You may be able to use the Post/Redirect/Get Design pattern (PRG). For more general information about Post/Redirect/Get please see the following: http://en.wikipedia.org/wiki/Post/Redirect/Get There are some nice process flow diagrams there.
A generic example of a view implementing PRG might look like the following:
# urls.py
urlpatterns = patterns('',
url(r'^/$', views.my_view, name='named_url'),
)
# forms.py
class MyForm(forms.Form):
pass # the form
# views.py
def my_view(request, template_name='template.html'):
""" Example PostRedirectGet
This example uses a request context, but isn't
necessary for the PRG
"""
if request.POST:
form = MyForm(request.POST)
if form.is_valid():
try:
form.save()
# on success, the request is redirected as a GET
return HttpResponseRedirect(reverse('named_url'))
except:
pass # handling can go here
else:
form = MyForm()
return render_to_response(template_name, {
'form':form
}, context_instance=RequestContext(request))
If you need to do something more interesting with the GET, reverse can take args and kwargs. Manipulate the view params, url_pattern, and reverse call to display the results you would like to see.
One additional note is that you don't have to redirect to the same view (as this example does). It could be any named view that you would like to redirect the user to.
current page is a very vague term but i am assuming you want the page that referred you to the form page, this is normally (not always) stored in the HTTP_REFERRER header of the request itself. You could try to fetch that from the request and do a redirect.

Resources