Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. from django.shortcuts import render
  2. from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView
  3. from .models import Post
  4. from .forms import PostForm
  5.  
  6.  
  7. class PostListView(ListView):
  8. queryset = Post.objects.all()
  9. template_name = 'post_view.html'
  10.  
  11. # override get_context_data for adding the last_viewed_post on the context
  12. def get_context_data(self,**kwargs):
  13. context = super().get_context_data(**kwargs)
  14. post_id = self.request.session.get('last_viewed_product_id',False)
  15. context['last_viewed_post'] = self.model.objects.get(id=post_id)
  16. return context
  17. # override the get_queryset for adding search feature
  18. def get_queryset(self):
  19. q = self.request.GET.get('q')
  20. query = Post.objects.all()
  21. if q :
  22. query = query.filter(description__contains=q)
  23. print(query)
  24. return query
  25. return query
  26.  
  27. class PostDetaiView(DetailView):
  28. model = Post
  29. template_name = 'post_detail.html'
  30.  
  31. # override the get_object for setting the last viewed product id on the session
  32. def get_object(self):
  33. post_id = self.kwargs['pk']
  34. self.request.session['last_viewed_product_id'] = post_id
  35. product_obj = self.model.objects.get(id=post_id)
  36. return product_obj
  37.  
  38.  
  39.  
  40. class PostCreateView(CreateView):
  41. model = Post
  42. form_class = PorductForm
  43. template_name = 'post_create.html'
  44. success_url = '/'
  45.  
  46. # override form_valid for setting the author before validate the form
  47. def form_valid(self,form):
  48. if request.user.is_autheticated :
  49. form.instance.author = request.user
  50. return super().form_valid(form)
  51.  
  52. class PostUpdateView(UpdateView):
  53. model = Post
  54. form_class= PorductForm
  55. template_name = 'post_update.html'
  56. success_url = '/'
  57.  
  58. # override form_valid for setting the last author that update the post before validate the form
  59. def form_valid(self,form):
  60. if request.user.is_autheticated :
  61. form.instance.last_update_by = request.user
  62. return super().form_valid(form)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement