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
664
votes
12 answers

How can I find script's directory?

Consider the following Python code: import os print os.getcwd() I use os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code…
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
501
votes
21 answers

Why does DEBUG=False setting make my django Static Files Access fail?

Am building an app using Django as my workhorse. All has been well so far - specified db settings, configured static directories, urls, views etc. But trouble started sneaking in the moment I wanted to render my own beautiful and custom 404.html and…
JWL
  • 13,591
  • 7
  • 57
  • 63
232
votes
18 answers

Class has no objects member

def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = {'latest_question_list':latest_question_list} return…
buuencrypted
  • 2,643
  • 2
  • 10
  • 8
226
votes
21 answers

How can I list urlpatterns (endpoints) on Django?

How can I see the current urlpatterns that "reverse" is looking in? I'm calling reverse in a view with an argument that I think should work, but doesn't. Any way I can check what's there and why my pattern isn't?
interstar
  • 26,048
  • 36
  • 112
  • 180
225
votes
7 answers

Django optional URL parameters

I have a Django URL like this: url( r'^project_config/(?P\w+)/(?P\w+)/$', 'tool.views.ProjectConfig', name='project_config' ), views.py: def ProjectConfig(request, product, project_id=None,…
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
188
votes
1 answer

Delete multiple objects in django

I need to select several objects to be deleted from my database in django using a webpage. There is no category to select from so I can't delete from all of them like that. Do I have to implement my own delete form and process it in django or does…
Dean
  • 8,668
  • 17
  • 57
  • 86
188
votes
13 answers

Disable a method in a ViewSet, django-rest-framework

ViewSets have automatic methods to list, retrieve, create, update, delete, ... I would like to disable some of those, and the solution I came up with is probably not a good one, since OPTIONS still states those as allowed. Any idea on how to do this…
db0
  • 3,689
  • 3
  • 23
  • 26
185
votes
13 answers

How to use permission_required decorators on django class-based views

I'm having a bit of trouble understanding how the new CBVs work. My question is this, I need to require login in all the views, and in some of them, specific permissions. In function-based views I do that with @permission_required() and the…
167
votes
8 answers

Django get the static files URL in view

I'm using reportlab pdfgen to create a PDF. In the PDF there is an image created by drawImage. For this I either need the URL to an image or the path to an image in the view. I managed to build the URL but how would I get the local path to the…
olofom
  • 6,233
  • 11
  • 37
  • 50
158
votes
14 answers

Django: TemplateDoesNotExist (rest_framework/api.html)

In my view function, I'd like to return a json object (data1) and some text/html (form). Is this possible? MY code @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): if request.is_ajax(): if request.method ==…
Coeus
  • 2,385
  • 3
  • 17
  • 27
142
votes
3 answers

Update only specific fields in a models.Model

I have a model class Survey(models.Model): created_by = models.ForeignKey(User) question = models.CharField(max_length=150) active = models.NullBooleanField() def __unicode__(self): return self.question and now I want to…
Registered User
  • 1,892
  • 4
  • 15
  • 15
142
votes
9 answers

What is the equivalent of "none" in django templates?

I want to see if a field/variable is none within a Django template. What is the correct syntax for that? This is what I currently have: {% if profile.user.first_name is null %}

--

{% elif %} {{ profile.user.first_name }} {{…
goelv
  • 2,774
  • 11
  • 32
  • 40
118
votes
4 answers

Django DoesNotExist

I am having issues on trying to figure "DoesNotExist Errors", I have tried to find the right way for manage the no answer results, however I continue having issues on "DoesNotExist" or "Object hast not Attribute DoestNotExists" from django.http…
Carlos
  • 4,299
  • 5
  • 22
  • 34
115
votes
5 answers

Django check for any exists for a query

In django how to check whether any entry exists for a query sc=scorm.objects.filter(Header__id=qp.id) This was how it was done in php if(mysql_num_rows($resultn)) { // True condition } else { // False condition }
Hulk
  • 32,860
  • 62
  • 144
  • 215
113
votes
6 answers

How to set up custom middleware in Django?

I'm trying to create a middleware to optionally pass a kwarg to every view that meets a condition. The problem is that I cannot find an example of how to set up the middleware. I have seen classes that override the method I want to,…
Atma
  • 29,141
  • 56
  • 198
  • 299
1
2 3
99 100