Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.shortcuts import render
- from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView
- from .models import Post
- from .forms import PostForm
- class PostListView(ListView):
- queryset = Post.objects.all()
- template_name = 'post_view.html'
- # override get_context_data for adding the last_viewed_post on the context
- def get_context_data(self,**kwargs):
- context = super().get_context_data(**kwargs)
- post_id = self.request.session.get('last_viewed_product_id',False)
- context['last_viewed_post'] = self.model.objects.get(id=post_id)
- return context
- # override the get_queryset for adding search feature
- def get_queryset(self):
- q = self.request.GET.get('q')
- query = Post.objects.all()
- if q :
- query = query.filter(description__contains=q)
- print(query)
- return query
- return query
- class PostDetaiView(DetailView):
- model = Post
- template_name = 'post_detail.html'
- # override the get_object for setting the last viewed product id on the session
- def get_object(self):
- post_id = self.kwargs['pk']
- self.request.session['last_viewed_product_id'] = post_id
- product_obj = self.model.objects.get(id=post_id)
- return product_obj
- class PostCreateView(CreateView):
- model = Post
- form_class = PorductForm
- template_name = 'post_create.html'
- success_url = '/'
- # override form_valid for setting the author before validate the form
- def form_valid(self,form):
- if request.user.is_autheticated :
- form.instance.author = request.user
- return super().form_valid(form)
- class PostUpdateView(UpdateView):
- model = Post
- form_class= PorductForm
- template_name = 'post_update.html'
- success_url = '/'
- # override form_valid for setting the last author that update the post before validate the form
- def form_valid(self,form):
- if request.user.is_autheticated :
- form.instance.last_update_by = request.user
- return super().form_valid(form)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement