Fakultas Ilmu Komputer UI

views.py 12.2 KB
Newer Older
1
2
3
4
import mimetypes
import os

from django.conf import settings
5
from django.contrib.auth.models import AnonymousUser
6
from django.core import serializers
7
from django.core.exceptions import PermissionDenied
8
from django.db.models import Q
9
10
11
12
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
from django.shortcuts import get_object_or_404, redirect, render
from django.template import loader
igor lestin sianipar's avatar
igor lestin sianipar committed
13
from django.views.generic import TemplateView, ListView
14
15
16
17
18

from authentication.models import User

from .forms import SuntingProfilForm, UploadMateriForm
from .models import Category, Comment, Materi
igor lestin sianipar's avatar
igor lestin sianipar committed
19

igor lestin sianipar's avatar
igor lestin sianipar committed
20
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
21
22

class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
23
    paginate_by = 2
24
25
26
27
28
29
30
    template_name = "app/katalog_materi.html"

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
31
        context["kategori_list"] = Category.objects.all()
32
        try:
33
34
            context["materi_list"] = Materi.objects.all().filter(
                status="APPROVE")
35
36
        except:
            context["materi_list"] = None
37

38
        getSearch = request.GET.get('search')
39
        if getSearch:
40
            list = Materi.objects.filter(
41
                Q(title__icontains=getSearch) |
42
                Q(author__icontains=getSearch) |
43
44
                Q(uploader__name__icontains=getSearch) |
                Q(descriptions__icontains=getSearch) |
45
                Q(publisher__icontains=getSearch)
46
47
            ).distinct()
            context["materi_list"] = list.filter(status="APPROVE")
Saul Andre's avatar
Saul Andre committed
48

49
50
51
        getKategori = request.GET.get("kategori")
        if getKategori:
            pkGet = request.GET.get("kategori")
52
53
54
55
            kategori = Category.objects.get(pk=pkGet)
            list = Materi.objects.filter(categories=kategori.pk)
            context["materi_list"] = list.filter(status="APPROVE")

56
        getSort = request.GET.get("sort")
57
58
        if getSort:
            list = Materi.objects.all().filter(status="APPROVE")
59
60
61
62
63
64
            if(getSort == "judul"):
                context["materi_list"] = list.order_by('title')
            elif(getSort == "penulis"):
                context["materi_list"] = list.order_by('author')
            elif(getSort == "pengunggah"):
                context["materi_list"] = list.order_by('uploader')
65

66
67
        return self.render_to_response(context=context)

68

69
70
71
72
73
74
75
76
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
77
        context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
78
79
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
80
        context["comment_data"] = query_set_for_comment
81
82
        return self.render_to_response(context=context)

83
84
    def get_user_name(self, request):
        user_name = ""
85
86
87
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
88
89
90
91
92
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

93
    def post(self, request, *args, **kwargs):
94
        commentText = request.POST.get("comment", None)
95
        if commentText == None or commentText == "":
96
97
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
98
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
99
100
            query_set_for_comment = Comment.objects.filter(
                materi=context["materi_data"])
101
            context["comment_data"] = query_set_for_comment
102
            return self.render_to_response(context=context)
103

104
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
105
        user_obj = request.user if request.user.is_authenticated else None
106
        print(user_obj)
107
108
        comment = Comment.objects.create(comment=commentText,
                                         username=self.get_user_name(request), materi=materi, user=user_obj)
109
110
111
        comment.save()
        return HttpResponseRedirect(request.path)

112

113
114
115
116
117
118
def delete_comment(request, pk_materi, pk_comment):
    comment = get_object_or_404(Comment, pk=pk_comment)
    url = '/materi/' + str(pk_materi) + "/"
    comment.delete()
    return HttpResponseRedirect(url)

119

120
121
122
123
124
125
126
127
def download_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
    path = materi.content.path
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        mimetype = mimetypes.guess_type(file_path)
        with open(file_path, "rb") as fh:
            response = HttpResponse(fh.read(), content_type=mimetype[0])
128
129
            response["Content-Disposition"] = "attachment; filename=" + \
                os.path.basename(file_path)
130
131
132
133
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")

134

135
136
137
138
139
140
141
142
def view_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
    path = materi.content.path
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        mimetype = mimetypes.guess_type(file_path)
        with open(file_path, "rb") as fh:
            response = HttpResponse(fh.read(), content_type=mimetype[0])
143
144
            response["Content-Disposition"] = "inline; filename=" + \
                os.path.basename(file_path)
145
146
147
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
148
149
150


class UploadMateriView(TemplateView):
151
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
152
153
154
155
156
157
    context = {}

    def get_context_data(self, **kwargs):
        context = super(UploadMateriView, self).get_context_data(**kwargs)
        return context

Saul Andre's avatar
Saul Andre committed
158
    def post(self, request, *args, **kwargs):
igor lestin sianipar's avatar
igor lestin sianipar committed
159
160
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
161
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
162
163
164
165
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.save()
166
167
168
            kateg = form.cleaned_data['categories']
            for i in kateg:
                materi.categories.add(i)
169
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
170
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
171
            context = self.get_context_data(**kwargs)
172
            context["form"] = form
igor lestin sianipar's avatar
igor lestin sianipar committed
173
174
175
176
177
178
            return self.render_to_response(context)

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
        context = self.get_context_data(**kwargs)
179
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
180
        return self.render_to_response(context)
181

Samuel Dimas's avatar
Samuel Dimas committed
182

183
184
185
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
186

187
188
189
190
191
192
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


193
class DashboardKontributorView(TemplateView):
194
    template_name = "dashboard.html"
195
196
197
198
199
200
201

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(DashboardKontributorView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
202
203
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
204
205
206
207
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
208
209
210
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
211
        return self.render_to_response(context)
212

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
class ProfilAdminView(TemplateView):
    template_name = "profil-admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(ProfilAdminView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProfilAdminView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        current_user = self.request.user
        context["user"] = current_user
        return self.render_to_response(context)
230

231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
class ProfilKontributorView(TemplateView):
    template_name = "profil.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(ProfilKontributorView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProfilKontributorView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        current_user = self.request.user
        context["user"] = current_user
        return self.render_to_response(context)

249

250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(SuntingProfilView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(SuntingProfilView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
268
        context["form"] = SuntingProfilForm(instance=current_user)
269
270
271
272
273
274
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
275
        current_user = self.request.user
276
277
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
278
        if form.is_valid():
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
279
            form.save()
280
281
282
283
284
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
285

286

287
288
289
290
291
292
293
class SuksesLoginKontributorView(TemplateView):
    template_name = "sukses_kontri.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(SuksesLoginKontributorView, self).dispatch(request, *args, **kwargs)
294

295
    def get_context_data(self, **kwargs):
296
297
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
298
299
300
301
302
303
304
305
306
307
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

        return self.render_to_response(context)

308

309
310
311
312
313
314
315
class SuksesLoginAdminView(TemplateView):
    template_name = "sukses_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_admin:
            raise PermissionDenied(request)
        return super(SuksesLoginAdminView, self).dispatch(request, *args, **kwargs)
316

317
318
319
320
321
322
323
324
325
326
327
328
    def get_context_data(self, **kwargs):
        context = super(SuksesLoginAdminView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

        return self.render_to_response(context)

329

Samuel Dimas's avatar
Samuel Dimas committed
330
331
332
333
334
335
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

336
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
337
338
339
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

340
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
341

342
        template = loader.get_template("error-404.html")
Samuel Dimas's avatar
Samuel Dimas committed
343
        return HttpResponse(template.render(context, request))