Fakultas Ilmu Komputer UI

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

from django.conf import settings
5
from django.contrib.auth.models import AnonymousUser
Saul Andre's avatar
Saul Andre committed
6
from django.contrib import messages
7
from django.core import serializers
8
from django.core.exceptions import PermissionDenied
9
from django.db.models import Q
10
11
12
13
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
14
from django.views.generic import TemplateView, ListView
15
16
17
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
18
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
19
20

class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
21
    paginate_by = 2
22
23
24
25
26
27
28
    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)
29
        context["kategori_list"] = Category.objects.all()
30
        try:
31
32
            context["materi_list"] = Materi.objects.all().filter(
                status="APPROVE")
33
34
        except:
            context["materi_list"] = None
35

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

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

54
        getSort = request.GET.get("sort")
55
56
        if getSort:
            list = Materi.objects.all().filter(status="APPROVE")
57
58
59
60
61
62
            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')
63

64
65
        return self.render_to_response(context=context)

66

67
68
69
70
71
72
73
74
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)
75
        context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
76
77
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
78
        context["comment_data"] = query_set_for_comment
79
80
        return self.render_to_response(context=context)

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

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

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

110

111
112
113
114
115
116
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)

117

118
119
120
121
122
123
124
125
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])
126
127
            response["Content-Disposition"] = "attachment; filename=" + \
                os.path.basename(file_path)
128
129
130
131
132
133
134
135
136
137
138
139
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")

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])
140
141
            response["Content-Disposition"] = "inline; filename=" + \
                os.path.basename(file_path)
142
143
144
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
145
146

class UploadMateriView(TemplateView):
147
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
148
149
150
151
152
153
    context = {}

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

Saul Andre's avatar
Saul Andre committed
154
    def post(self, request, *args, **kwargs):
igor lestin sianipar's avatar
igor lestin sianipar committed
155
156
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
157
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
158
159
160
161
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.save()
162
163
164
            kateg = form.cleaned_data['categories']
            for i in kateg:
                materi.categories.add(i)
Saul Andre's avatar
Saul Andre committed
165
166
            
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
167
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
168
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
169
            context = self.get_context_data(**kwargs)
170
            context["form"] = form
Saul Andre's avatar
Saul Andre committed
171
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
172
173
174
175
176
177
            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)
178
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
179
        return self.render_to_response(context)
180

Samuel Dimas's avatar
Samuel Dimas committed
181

182
183
184
185
186
187
188
189
190
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


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

    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):
200
201
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
202
203
204
205
        return context

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

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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)
228

229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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)

247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
266
        context["form"] = SuntingProfilForm(instance=current_user)
267
268
269
270
271
272
        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
273
        current_user = self.request.user
274
275
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
276
        if form.is_valid():
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
277
            form.save()
278
279
280
281
282
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
283

284

285
286
287
288
289
290
291
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)
292

293
    def get_context_data(self, **kwargs):
294
295
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
296
297
298
299
300
301
302
303
304
305
        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)

306

307
308
309
310
311
312
313
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)
314

315
316
317
318
319
320
321
322
323
324
325
326
    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)

327

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

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

338
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
339

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