Questions tagged [django-views]

Django views are MVC views; they control rendering (typically through templates), and the data displayed.

Django views are MVC views; they control rendering (typically through templates) and the data displayed.

It is possible to create generic views, which are specialised on various parameters (frequently model classes), which are simply paired with an appropriate template to create a complete page.

The separation from the template system also makes it very easy to create output in different formats, or use one view for several, quite different looking pages (usually with similar data).

There are two types of views: the Class based view (CBV for short) and Function based views (FBV). The use cases differ for each one and whilst later versions of Django advocate the use of Class based views the Function based views aren't fully deprecated.

CBV's enables better code reuse, inheritance and mixins. Further reading can be found here

An example of a Class based view:

from django.views.generic import UpdateView
from myapp.models import Author

class AuthorUpdate(UpdateView):
    model = Author
    fields = ['name']
    template_name_suffix = '_update_form'

An example of a Function based view:

def update_account_view(request, account_id):
    # Do some account stuff
    context = {'account': some_object, 'another_key': 'value'}
    return render_to_response('templates/account_update.html', 
                              context, 
                              context_instance=RequestContext(request))
24045 questions
70
votes
7 answers

How to redirect to previous page in Django after POST request

I face a problem which I can't find a solution for. I have a button in navbar which is available on all pages and it is a button responsible for creating some content. View that links with button: def createadv(request): uw =…
Oleg
  • 777
  • 1
  • 6
  • 10
69
votes
5 answers

Use get_queryset() method or set queryset variable?

These two pieces of code are identical at the first blush: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_poll_list' queryset = Poll.active.order_by('-pub_date')[:5] and class…
9Algorithm
  • 1,258
  • 2
  • 16
  • 22
68
votes
7 answers

django: return string from view

I know this is a simple question, sorry. I just want to return a simple string, no templates. I have my view: def myview(request): return "return this string" I don't remember the command. Thanks
KingFish
  • 8,773
  • 12
  • 53
  • 81
67
votes
1 answer

How does the order of mixins affect the derived class?

Say, I have the following mixins that overlaps with each other by touching dispatch(): class FooMixin(object): def dispatch(self, *args, **kwargs): # perform check A ... return super(FooMixin, self).dispatch(*args,…
66
votes
2 answers

How do I send empty response in Django without templates

I have written a view which responds to ajax requests from browser. It's written like so - @login_required def no_response(request): params = request.has_key("params") if params: # do processing var = RequestContext(request,…
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
64
votes
1 answer

Django ImportError: cannot import name 'render_to_response' from 'django.shortcuts'

After upgrading to Django 3.0, I get the following error: ImportError: cannot import name 'render_to_response' from 'django.shortcuts' My view: from django.shortcuts import render_to_response from django.template import RequestContext def…
Alasdair
  • 298,606
  • 55
  • 578
  • 516
64
votes
4 answers

Django 1.11 TypeError context must be a dict rather than Context

Just received the Sentry error TypeError context must be a dict rather than Context. on one of my forms. I know it has something to do with Django 1.11, but I am not sure what to change to fix it. Offending line message =…
Charles Smith
  • 3,201
  • 4
  • 36
  • 80
61
votes
4 answers

Example of Django Class-Based DeleteView

Does anyone know of or can anyone please produce a simple example of Django's class-based generic DeleteView? I want to subclass DeleteView and ensure that the currently logged-in user has ownership of the object before it's deleted. Any help would…
Lockjaw
  • 1,882
  • 2
  • 16
  • 15
60
votes
8 answers

Django - Getting last object created, simultaneous filters

Apologies, I am completely new to Django and Python. I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first…
zdyn
  • 2,155
  • 1
  • 15
  • 17
59
votes
1 answer

Django print choices value

EMP_CHOICES = ( (0,'-- Select --'), (1,'Good'), (2,'Average'), ) class EMPFeedback(models.Model): user_choices = models.IntegerField(choices=EMP_CHOICES) If the value stored in the db as 1 for user_choices how…
Rajeev
  • 44,985
  • 76
  • 186
  • 285
59
votes
7 answers

The view didn't return an HttpResponse object. It returned None instead

I have the following simple view. Why is it resulting in this error? The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead. """Renders web pages for the user-authentication-lifecycle…
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
58
votes
7 answers

CSRF verification failed. Request aborted. on django

I am following Django 1.3 Web Development. and for logins, i am getting the following error Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. This is my settings.py…
Yousuf Jawwad
  • 3,037
  • 7
  • 33
  • 60
58
votes
3 answers

Best way to write an image to a Django HttpResponse()

I need to serve images securely to validated users only (i.e. they can't be served as static files). I currently have the following Python view in my Django project, but it seems inefficient. Any ideas for a better way? def…
k-g-f
  • 1,123
  • 2
  • 10
  • 11
56
votes
7 answers

Difference between reverse() and reverse_lazy() in Django

I understand that we can use reverse() in FBV and reverse_lazy() in CBV. I understand that we have to use reverse_lazy() in CBV as the urls are not loaded when the file is imported (Ref: Reverse_lazy and URL Loading?) What I don't understand is:…
RyuCoder
  • 1,714
  • 2
  • 13
  • 21
56
votes
16 answers

Unable to import path from django.urls

Tried to run command: from django.urls import path Getting error: Traceback (most recent call last): File "< stdin >", line 1, in ImportError: cannot import name 'path' I am using django version 1.11
Lev
  • 999
  • 2
  • 10
  • 26