I am trying to call a stored procedure in Django that returns some data based on which batch number you give it. In my database if I write
call InkItUp.InkBatchNumberCallBackk(15137);
I return the data I need. But then I try to use Postman to call the URL I have defined for the view saveInkbatch in my urls.py file It gives me this error:
The view api.views.saveInkbatch didn't return an HttpResponse object. It returned None instead.
Me urls.py look something like this:
path('createsp/', views.saveInkbatch),
and there is the method in the view.py
#csrf_exempt
def saveInkbatch(request):
if request.method == 'POST':
if request.POST.get('batchnumber'):
save=Ink()
save.batchnumber=request.POST.get('batchnumber')
cursor=connection.cursor()
cursor.execute("call InkItUp.InkBatchNumberCallBackk('"+save.batchnumber+"')")
messages.success(request, "The batchnumber "+save.batchnumber+"")
return HttpResponse(request, content_type = 'application/json')
If you know a way to call a stored procedure from MySQl with a class-based view - It would be nice to. I would much rather use class-based views if possibly.
Related
In my project I'm trying to hit a url(which is running in same project) in my view.
so in simplest way I can explain here.
#login_required
def my_api_view(request):
if requests.method == 'GET':
# do stuff
return JsonResponse()
# and its url is `/api/get-info/`
another view which is consuming above api
#login_required
def show_info(request):
url = get_base_url + /api/get-info/ # http://localhost:8000/api/get-info/
r = requests.get(url)
return HttpResponse(r.json())
Now I have to use same session (login required) so when I hit the url using requests it complains that user is not loggedin which is obviously correct.
How can I do this elegantly and efficienty. session use of logged in user. (I dont want to call the view as a function, I want to hit the api-url end point and consume.
PS: we have something similar in django Test self.client.get(...)
Just call that view function and pass the request object as parameter to it.
#login_required
def show_info(request):
r = my_api_view(request)
return HttpResponse(r.json())
Or a better option would be to simply separate the logic into a separate function, as mentioned by #koniiiik in the comments.
EDIT: Or if you really want to hit the URL endpoint, you can simply pass on the cookie values to the request you make.
#login_required
def show_info(request):
url = get_base_url + "/api/get-info/" # http://localhost:8000/api/get-info/
r = requests.get(url, cookies=request.COOKIES)
return HttpResponse(r.json())
Below is the code from views.py where I am using render_to_response to direct the user to done.html along with a dictionary of variables. But, I actually want to direct the user to a url /home_main/#signin_completeand pass the dictionary of variables that are callable. Can someone please suggest if there is a way of doing this ?
def done(request):
"""Login complete view, displays user data"""
scope = ' '.join(GooglePlusAuth.DEFAULT_SCOPE)
return render_to_response('done.html', {
'user': request.user,
'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
'plus_scope': scope
}, RequestContext(request))
EDIT
My requirement is to render a second page (signin_complete) from a multipage html (home_main.html). Currently, I am achieving this by redirecting the user with HttpResponseRedirect as shown below. But, I would also like to pass a callable dictionary that I can use in the second page of the multipage html.
Here is a link that gives more information of a multipage html under multipage template structure.
def done(request):
"""Login complete view, displays user data"""
scope = ' '.join(GooglePlusAuth.DEFAULT_SCOPE)
return HttpResponseRedirect('/home_main/#signin_complete')
Below is the dictionary that I would like to pass to the second page (sign_complete) in the multi page html.
{
'user': request.user,
'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
'plus_scope': scope
}
The session is the place to store data between requests.
# in done():
request.session['dict_to_save'] = my_dict_to_save
return redirect('/new/url/to/redirect/to')
# in the new view:
values_from_session = request.session.pop('dict_to_save', None)
It would be much better if you would redirect request inside done() method, like the docs advises you to do.
This solves your issue as well, since you can define your own url to redirect to, there's related SO question of how to add hash tags when redirecting.
I am trying to allow registration (using this django-registration register view) to one of my applications from a modal dialog.
Since this form is in a modal box, I'd like to get an json reponse on success (instead of the default redirection)
How can I use this view (django-registration register) to manage the registration and send back a json response on success ?
I know how to make ajax/json responses, the question is how to use the django-registration view without the redirection behavior or wrap it into an other view to manage the response.
First you need to change the urls.py to wrap the existing view with another functionality. To do that you have to create a new backend package in backends folder and change urls.py there while keeping everything else intact, or you could just go ahead and modify the existing urls.py in the backend package.
I have not tested this, but it should work.
Point url to the new view:
# urls.py
url(r'^register/$', register_wrap,
{'backend': 'registration.backends.default.DefaultBackend'},
name='registration_register'),
# your new view that wraps the existing one
def register_wrap(request, *args, **kwargs):
# call the standard view here
response = register(request, *args, **kwargs)
# check if response is a redirect
if response.status_code == 302:
# this was redirection, send json response instead
else:
# just return as it is
return response
If you are going to need this for more views you can just create a decorator using this.
Why I would do is to check if request.is_ajax() in your normal after-successfull-registration-redirect view and return json response there.
You ask how you can use the existing view to manage the registration and send back a json response on success. Since the HttpResponseRedirect is pretty much hard coded in the view, you can't use the view as it is. Instead, either fork it, or write your own view and change the urls.py so that r'^register/$' directs to your new view.
As far as the json response is concerned, on success you can do something like this:
from django.utils import simplejson as json
def register_ajax(request):
...
return HttpResponse(json.dumps(dict(success=True, **dict_containing_data)))
Hope this helps
I have a situation (shopping cart checkout sequence) where the workflow used in Django's FormPreview contrib app looks perfect, except I need to have some view logic occur before I call it (I can't call the checkout sequence if the cart is empty, for example). From the docs, it looks like you call FormPreview directly from the urlconf like so:
(r'^post/$', SomeModelFormPreview(SomeModelForm))
...and it calls the overridden done() method for the FormPreview directly (without a view).
Since my urls.py is similar to:
url(r'^checkout/$', 'checkout', {'SSL': settings.ENABLE_SSL }, name = 'checkout'),
and my view is similar to:
def checkout(request):
if cart.empty(request):
cart = urlresolvers.reverse('shopping_cart')
return HttpResponseRedirect(cart)
if request.method == 'POST':
checkoutform = CheckoutFormPreview(CheckoutForm)
This last line is where I'd like to call it, but can't figure out how to wrap it... Suggestions?
It looks like CheckoutFormPreview(CheckoutForm) returns a callable view that you can add to your url config. If you call it in your view, you just need to pass the required request argument. Then return the result.
Putting it together, you have (untested):
if request.method == 'POST':
form_preview_view = CheckoutFormPreview(CheckoutForm)
return form_preview_view(request)
is there a way i can pass json format data through django HttpResponse. I am trying to call the view through prototype ajax and return json format data.
Thanks
You could do something like this inside your app views.py
import json
def ajax_handler(req, your_parameter):
json_response = json.dumps(convert_data_to_json)
return HttpResponse(json_response,mimetype='application/json')
Building on Lombo's answer, you might want to utilize the request.is_ajax() method. This checks the HTTP_X_REQUESTED_WITH header is XmlHttpRequest.
This is a good way to avoid sending a json response to a regular GET - which I guess at worst is just confusing to your users, but also lets you use the same view for ajax vs. non-ajax requests. This approach makes it easier to build apps that degrade gracefully.
For example:
def your_view(request):
data_dict = # get some data
if request.is_ajax():
# return json data for ajax request
return HttpResponse(json.dumps(data_dict),mimetype='application/json')
# return a new page otherwise
return render_to_response("your_template.html", data_dict)
This approach works particularly well for form processing also.