Skip to content

Instantly share code, notes, and snippets.

@vikas-git
Last active October 9, 2019 09:00
Show Gist options
  • Save vikas-git/17e51192f12cdb64acf52fcac716ce7c to your computer and use it in GitHub Desktop.
Save vikas-git/17e51192f12cdb64acf52fcac716ce7c to your computer and use it in GitHub Desktop.
Different types of Generic views
LIST VIEW:
from django.views.generic import ListView
** Simple example
class UsersListView(ListView):
model = User
** You can add attributes to change the default behaviour.
class UsersListView(ListView):
model = User
context_object_name = 'my_user_list' # your own name for the list as a template variable
queryset = User.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
template_name = 'users/my_arbitrary_template_name_list.html' # Specify your own template name/location
** Overriding methods
class UsersListView(ListView):
model = User
def get_queryset(self):
return User.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
** override get_context_data() in order to pass additional context variables to the template
class UsersListView(ListView):
model = User
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(UsersListView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['some_data'] = 'This is just some data'
return context
DETAIL VIEW:
URL file:
urlpatterns = [
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
]
View File :
from django.views.generic import DetailView
** simple example :
class BookDetailView(DetailView):
model = Book
FORM VIEW:
View File:
from django.views.generic import FormView
** Simple example
class ContactView(FormView):
form_class = ContactForm
template_name = 'contact-us.html'
success_url = reverse_lazy('<app-name>:contact-us')
def form_valid(self, form):
self.send_mail(form.cleaned_data)
return super(ContactView, self).form_valid(form)
** Add Additional data
class ContactView(FormView):
form_class = ContactForm
template_name = 'contact-us.html'
success_url = reverse_lazy('<app_name>:contact-us')
def get_initial(self):
initial = super(ContactView, self).get_initial()
if self.request.user.is_authenticated:
initial.update({'name': self.request.user.get_full_name()})
return initial
def form_valid(self, form):
self.send_mail(form.cleaned_data)
return super(ContactView, self).form_valid(form)
CREATE VIEW :
View File:
from django.views.generic import CreateView
** Simple Example
class BookCreateView(CreateView):
template_name = 'books/book-create.html'
form_class = BookCreateForm
** Adding initial data to CreateView
class BookCreateView(CreateView):
template_name = 'books/book-create.html'
form_class = BookCreateForm
def get_initial(self, *args, **kwargs):
initial = super(BookCreateView, self).get_initial(**kwargs)
initial['title'] = 'My Title'
return initial
UPDATE VIEW:
** view file:
class PostUpdateView(UpdateView):
model = Post
fields = ('message', )
template_name = 'edit_post.html'
pk_url_kwarg = 'post_pk'
context_object_name = 'post'
def form_valid(self, form):
post = form.save(commit=False)
post.updated_by = self.request.user
post.updated_at = timezone.now()
post.save()
return redirect('topic_posts', pk=post.topic.board.pk, topic_pk=post.topic.pk)
** Note : With the UpdateView and the CreateView, we have the option to either define form_class or the fields attribute. In the example above we are using the fields attribute to create a model form on-the-fly.
DELETE VIEW :
** view file :
from django.views.generic import DeleteView
from django.http import Http404
class MyDeleteView(DeleteView):
def get_object(self, queryset=None):
""" Hook to ensure object is owned by request.user. """
obj = super(MyDeleteView, self).get_object()
if not obj.owner == self.request.user:
raise Http404
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment