Get request.session from a class-based generic view

You have access to self.request from anywhere within the class (and therefore self.request.session) https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#dynamic-filtering The key part to making this work is that when class-based views are called, various useful things are stored on self; as well as the request (self.request) this includes the positional (self.args) and name-based (self.kwargs) arguments captured according to the URLconf.

Raise 404 and continue the URL chain

This is certainly view logic; all urls.py is for is for matching URL patterns, not performing validation. You can use the Http404 exception to handle this. from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response(‘polls/detail.html’, {‘poll’: p}) Alternatively, you may find the get_object_or_404 or get_list_or_404 methods, which …

Read more

Can I have a Django form without Model

Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm, except that you are not bound by the model, and you have to explicitly declare all the form attributes. def form_handle(request): form = MyForm() if request.method==’POST’: form = MyForm(request.POST) if form.is_valid(): …

Read more

django-admin: Add extra row with totals

Yes, you can do it in many ways, but most django-ist way to do is: First override the default django listing view… And give a new template file directory ModelAdmin.changelist_view(self, request, extra_context=None) Like: class MyModelAdmin(admin.ModelAdmin): # A template for a very customized change view: change_list_template=”admin/myapp/extras/sometemplate_change_form.html” def get_total(self): #functions to calculate whatever you want… total = …

Read more

Execute code in Django after response has been sent to the client

The method I am going for at the moment uses a subclass of HttpResponse: from django.template import loader from django.http import HttpResponse # use custom response class to override HttpResponse.close() class LogSuccessResponse(HttpResponse): def close(self): super(LogSuccessResponse, self).close() # do whatever you want, this is the last codepoint in request handling if self.status_code == 200: print(‘HttpResponse successful: …

Read more

AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context

You’re getting this error as the HyperlinkedIdentityField expects to receive request in context of the serializer so it can build absolute URLs. As you are initializing your serializer on the command line, you don’t have access to request and so receive an error. If you need to check your serializer on the command line, you’d …

Read more