1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import TemplateView from bbs.models import Article
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.contrib import messages
class ArticleListView(TemplateView): template_name = 'article_list.html' queryset = None
def get(self, request, *args, **kwargs): print(request.GET) ctx = { 'view': self.__class__.__name__, 'articles': self.get_queryset() } return self.render_to_response(ctx)
def get_queryset(self): if not self.queryset: self.queryset = Article.objects.all() return self.queryset
class ArticleDetailView(TemplateView): template_name = 'article_detail.html' queryset = Article.objects.all() pk_url_kwargs = 'article_id'
def get_object(self, queryset=None): queryset = queryset or self.queryset pk = self.kwargs.get(self.pk_url_kwargs) return queryset.filter(pk=pk).first()
if not article: raise Http404('invalid pk') return article
def get(self, request, *args, **kwargs): article = self.get_object() ctx = { 'view': self.__class__.__name__, 'article': article } return self.render_to_response(ctx)
@method_decorator(csrf_exempt, name='dispatch') class ArticleCreateUpdateView(TemplateView): template_name = 'article_update.html' queryset = Article.objects.all() pk_url_kwargs = 'article_id'
def get_object(self, queryset=None): queryset = queryset or self.queryset pk = self.kwargs.get(self.pk_url_kwargs) article = queryset.filter(pk=pk).first()
if pk and not article: raise Http404('invalid pk') return article
def get(self, request, *args, **kwargs): article = self.get_object() ctx = { 'article': article } return self.render_to_response(ctx)
def post(self, request, *args, **kwargs): action = request.POST.get('action') post_data = {key: request.POST.get(key) for key in ('title', 'content', 'author')} for key in post_data: if not post_data[key]: messages.error(self.request, '{} 값이 존재하지 않습니다.'.format(key), extra_tags='danger') if len(messages.get_messages(request)) == 0: if action == 'create': article = Article.objects.create(**post_data) messages.success(self.request, '게시글이 저장되었습니다.') elif action == 'update': article = self.get_object() for key, value in post_data.items(): setattr(article, key, value) article.save() messages.success(self.request, '게시글이 성공적으로 수정되었습니다.', extra_tags='info') else: messages.error(self.request, '알 수 없는 요청입니다.', extra_tags='danger') return HttpResponseRedirect('/article/') ctx = { 'article': self.get_object() if action == 'update' else None } return self.render_to_response(ctx)
|