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
113
votes
7 answers

Django class-based view: How do I pass additional parameters to the as_view method?

I have a custom class-based view # myapp/views.py from django.views.generic import * class MyView(DetailView): template_name = 'detail.html' model = MyModel def get_object(self, queryset=None): return…
user9903
112
votes
7 answers

In django do models have a default timestamp field?

In django - is there a default timestamp field for all objects? That is, do I have to explicitly declare a 'timestamp' field for 'created on' in my Model - or is there a way to get this automagically?
9-bits
  • 10,395
  • 21
  • 61
  • 83
109
votes
8 answers

django @login_required decorator for a superuser

Is there a decorator in django similar to @login_required that also tests if the user is a superuser? Thanks
ChristopherDBerry
  • 1,722
  • 3
  • 11
  • 19
108
votes
2 answers

Django request get parameters

In a Django request I have the following: POST: How do I get the values of section and MAINS? if request.method == 'GET': qd = request.GET elif request.method == 'POST': qd =…
Hulk
  • 32,860
  • 62
  • 144
  • 215
108
votes
4 answers

Django reverse lookup of foreign keys

I have a venue, this venue has many events happening there. My models look like this: class Venue(models.Model): title = models.CharField(max_length=200) date_published = models.DateTimeField('published date',default=datetime.now,…
FLX
  • 4,634
  • 14
  • 47
  • 60
107
votes
4 answers

What is the right way to validate if an object exists in a django view without returning 404?

I need to verify if an object exists and return the object, then based on that perform actions. What's the right way to do it without returning a 404? try: listing = RealEstateListing.objects.get(slug_url = slug) except: listing = None if…
Rasiel
  • 2,823
  • 6
  • 31
  • 37
101
votes
8 answers

django - get() returned more than one topic

When I tried to relate an attribute with another one which has an M to M relation I received this error: get() returned more than one topic -- it returned 2! Can you guys tell me what that means and maybe tell me in advance how to avoid this error…
BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70
99
votes
5 answers

How to change status of JsonResponse in Django

My API is returning a JSON object on error but the status code is HTTP 200: response = JsonResponse({'status': 'false', 'message': message}) return response How can I change the response code to indicate an error?
Dhanushka Amarakoon
  • 3,502
  • 5
  • 31
  • 43
96
votes
7 answers

Can I call a view from within another view?

One of my view needs to add an item, along with other functionality, but I already have another view which specifically adds an item. Can I do something like: def specific_add_item_view(request): item = Item.objects.create(foo=request.bar) def…
john2x
  • 22,546
  • 16
  • 57
  • 95
96
votes
7 answers

Class Based Views VS Function Based Views

I always use FBVs (Function Based Views) when creating a django app because it's very easy to handle. But most developers said that it's better to use CBVs (Class Based Views) and use only FBVs if it is complicated views that would be a pain to…
catherine
  • 22,492
  • 12
  • 61
  • 85
94
votes
11 answers

How to get primary keys of objects created using django bulk_create

Is there a way to get the primary keys of the items you have created using the bulk_create feature in django 1.4+?
mikec
  • 3,543
  • 7
  • 30
  • 34
92
votes
9 answers

How do I return JSON without using a template in Django?

This is related to this question: Django return json and html depending on client python I have a command line Python API for a Django app. When I access the app through the API it should return JSON and with a browser it should return HTML. I can…
Neeran
  • 1,753
  • 3
  • 21
  • 26
91
votes
3 answers

How to handle request.GET with multiple variables for the same parameter in Django

In a Django view you can access the request.GET['variablename'], so in your view you can do something like this: myvar = request.GET['myvar'] The actual request.GET['myvar'] object type is: Now, if you want to pass…
ismail
  • 3,882
  • 5
  • 36
  • 47
89
votes
7 answers

Django 2.0 path error ?: (2_0.W001) has a route that contains '(?P<', begins with a '^', or ends with a '$'

I'm trying to create the back-end code for a music application on my website. I have created the correct view in my views.py file (in the correct directory) as shown below: def detail(request, album_id): return HttpResponse("

Details for…

Joe Tynan
  • 895
  • 1
  • 6
  • 5
87
votes
4 answers

'RelatedManager' object is not iterable Django

Hey i have looked around through some simliar posts here on SO but havent found anything that has solved my problem. I have the following models, from django.db import models class Areas(models.Model): name = models.CharField(max_length =…
Mike Waites
  • 1,688
  • 3
  • 19
  • 26