Django page redirect with pre-processing - django

I'm trying to implement a generic view that performs some pre-processing and redirects to an external website. Essentially I want to query and update the database before performing the redirect each time the view is accessed.
I spotted Python + Django page redirect but this only deals with simple redirects and not with generic views.
Can anyone provide an example on how this should be implemented?
Any help you can give would be greatly appreciated,
Niall

If you just want to do some processing before performing a redirect, I'm not seeing how generic views come into play for you. You can customize generic views by wrapping them in another function, or in the case of class-based generic views, subclassing them. In your situation, I fail to see how they'd benefit you much, just write a normal view, and use redirect:
from django.shortcuts import redirect
def my_view(request):
...do some processing
return redirect('/some/url/')
Not going to get easier than that.

Related

Single-page login in Django app

I'm currently using out-of-the-box django.contrib.auth to handle authentication in my Django app. This means that the user starts at a log in page and is redirected to the app on successful login. I would like to make my app single-page, including this login process, where a redirect doesn't happen, but maybe a "hot" template switch-out or some fancy client-side div magic (that still remains secure). My Google searching turned up pretty short, the closest solution dealing with putting a log in form on every page.
Any direction or ideas here would be much appreciated. I would obviously prefer to work within the existing confines of django.contrib.auth if possible, but I'm open to all solutions.
I'm not sure I understand your question completely. I think you want to have a single page. If so, put logic in your template that checks to see if the user is authenticated. If not, display a login form that POSTS to the appropriate django.contrib.auth view. You can supply an argument to this view to have it redirect back to your page. When you come back, the user will be authenticated, so you won't display the login form.
Have a look at Django-Easy-Pjax https://pypi.python.org/pypi/django-easy-pjax - it works like a charm and is well documented. Everything you like is being made with AJAX requests: links, forms using GET and forms using POST.
Essentially you only need to add a data-pjax="#id_of_the_container_where_the_result_goes" attribute in your a and form tags.
And the great thing about it: It updates the title and location bar of your browser.
One caveat: If you want to upload files in some form, this is not supported by Easy-Pjax, so you might want to use some workaround jQuery library for that.

Profiling for Django + Tastypie

What is the best tool to do profiling on a Django app that uses Tastypie (all responses or JSON, so django_toolbar is no good in this case)?
One potential solution is to create a view which just renders TastyPie responses as HTML. This will allow django-debug-toolbar to output correct profiling data. The following is a fairly quick and dirty attempt at this.
In urls.py:
Just add the following line to your url patterns, but make sure it is only included if debugging is enabled.
(r'^api_profile/(?P<resource>.*)$', 'common.views.api_profile')
In common/views.py:
Place this view anywhere you want, I've put it in my common app.
from django.shortcuts import render_to_response
# Import the tastypie.api.Api object with which your api resources are registered.
from apps.api.urls import api
def api_profile(request, resource):
""" Allows easy profiling of API requests with django-debug-toolbar. """
context = {}
resource = resource.strip('/')
resource = api.canonical_resource_for(resource)
obj_list = resource.wrap_view('dispatch_list')(request)
response = resource.create_response(request, obj_list)
context['api_response'] = response
return render_to_response('common/api_profile.html', context)
In templates/common/api_profile.html:
Include a very simple template.
<body>
{{api_response}}
</body>
Now you could just navigate to '/api_profile/a_resource/' with django-debug-toolbar enabled and get profiling data for the generation of the a_resource list view. Request parameters can also be used, e.g. I've been profiling the request 'api_profile/posts/?limit=8&offset=16'.
I've never actually tried profiling a django application. But some time ago I've read an interesting article about this subject.
http://reinout.vanrees.org/weblog/2012/04/18/profiling-python.html
New Relic is good if you want to pay. You can also use hotshot profiler in https://github.com/shaunsephton/django-snippetscream for a quick peek at whats going on
I use this middleware -> https://djangosnippets.org/snippets/2126/
As the comment states, just
Install this by adding it to your MIDDLEWARE_CLASSES. It is active
if you are logged in as a superuser, or always when settings.DEBUG
is True.
To use it, pass 'profile=1' as a GET or POST parameter to any HTTP
request.
It will create an interactive HTML showing queries executed, time, methods... you should give it a try!

How to post json to Django

What is the proper way to post json to Django? I have tried to use views, but I am not certain how to handle csrf. Is there another way to bypass views and simply accept a post of json?
Views are what handle the post data. There is no concept of "bypass views" because that is where the work of processing a request is done.
This is probably what your are looking for:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
This shows you how to handle csrf tokens with ajax (namely by using cookies).
I also might suggest you slow down and try to work through the tutorial found here:
https://docs.djangoproject.com/en/dev/intro/tutorial01/
You will likely have an easier time with django if you undertstand how the pieces (Models, Views, Templates, urls, Forms, etc) fit together.
Since you've added that these are API calls the simplest thing to do would be to mark these views as csrf_exempt. Additionally, as you might guess creating an API from models is a common task (I'm assuming that your API maps to models as that's the common case and you haven't specified) you may want to not reinvent the wheel and instead use piston or tastypie to make this easier on you: http://djangopackages.com/grids/g/api/
Use the #csrf_exempt decorator on any API views.

Whats the best way to display message after CRUD operation In Django

I have been doing CRUD operation in Django but I am having problem with what to do after successful operation.
Is there any way that i can redirect the user to Home page with small message on top of page like
"Record Successfully added or something else" like Google does with Dismiss hyperlink :)
EDIT:
Actually that a is full documentation and not a simple example.
I could not understand in which template I have to include {{messages}} in. In update form, edit form or home page form?
I don't understand where I need to define messages. I use only generic views so I am confused.
Use the django.contrib.messages framework to get the same messaging style as used in Django admin.
Enable the middleware module by adding 'django.contrib.sessions.middleware.SessionMiddleware' to MIDDLEWARE_CLASSES in settings.py.
In your view, use something like messages.add_message(request, messages.INFO, 'Stuff happened') to record information where it makes sense.
In your template, you'll have a list messages which you can iterate over where it makes sense in your design - the example in the documentation shows a full example which exposes the tags as CSS classes for ease of styling.

Redirecting to a page

I am facing a problem: I want to give a link in my change form that will redirect to a page which may be simple php page also or any page, in that page I want to perform some db queries and display them. I also wan to pass id on click. Is it possible?
In my view.py I wrote:
from django.shortcuts import render_to_response
from django.template import RequestContext
def MyClass(self,id,request):
return render_to_response('admin/custom_change_form.html')#my template location
My model and admin files are simple.
To send to a file directly, use direct_to_template(). You can pass anything in the url that you like - just give the information to your template, and write it in the url. After all, Django doesn't require url helpers.
I sense that whatever you're trying to do is some god-awful hackish thing that would be much better served by doing it all in Django.
You will need to override your change form for that model and display whatever you would like. But that is making the assumption you are talking about the contrib admin within Django.
Realistically you have not provided sufficient information for anyone to accurately answer your question.