Fakultas Ilmu Komputer UI

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

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

21
22
23
24
25
26
27
28
29

class DaftarKatalog(TemplateView):
    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)
30
        context["kategori_list"] = Category.objects.all()
31
        try:
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
39
            list = Materi.objects.filter(
                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
                ).distinct()
45
            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
            kategori = Category.objects.get(pk = pkGet)
            list = Materi.objects.filter(categories = kategori.pk)
52
            context["materi_list"] = list.filter(status = "APPROVE")
53
            
54
        getSort = request.GET.get("sort")
55
        if getSort: 
56
            list = Materi.objects.all().filter(status = "APPROVE")
57
58
59
60
61
62
63
            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')
        
64
65
66
67
68
69
70
71
72
73
        return self.render_to_response(context=context)

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

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

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

105
106
107
108
109
110
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)

111
112
113
114
115
116
117
118
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])
119
120
            response["Content-Disposition"] = "attachment; filename=" + \
                os.path.basename(file_path)
121
122
123
124
125
126
127
128
129
130
131
132
            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])
133
134
            response["Content-Disposition"] = "inline; filename=" + \
                os.path.basename(file_path)
135
136
137
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
138
139
140


class UploadMateriView(TemplateView):
141
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
142
143
144
145
146
147
    context = {}

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

Saul Andre's avatar
Saul Andre committed
148
    def post(self, request, *args, **kwargs):
igor lestin sianipar's avatar
igor lestin sianipar committed
149
150
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
151
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
152
153
154
155
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.save()
156
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
157
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
158
            context = self.get_context_data(**kwargs)
159
            context["form"] = form
igor lestin sianipar's avatar
igor lestin sianipar committed
160
161
162
163
164
165
            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)
166
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
167
        return self.render_to_response(context)
168

Samuel Dimas's avatar
Samuel Dimas committed
169

170
171
172
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
173

174
175
176
177
178
179
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


180
class DashboardKontributorView(TemplateView):
181
    template_name = "dashboard.html"
182
183
184
185
186
187
188
189
190
191
192
193

    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):
        context = super(DashboardKontributorView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
194
195
196
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
197
        return self.render_to_response(context)
198

199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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)

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
235
        context["form"] = SuntingProfilForm(instance=current_user)
236
237
238
239
240
241
        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
242
243
        current_user = self.request.user
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
244
        if form.is_valid():
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
245
            form.save()
246
247
248
249
250
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
251

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
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)
    
    def get_context_data(self, **kwargs):
        context = super(SuksesLoginKontributorView, 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)

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)
    
    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)

Samuel Dimas's avatar
Samuel Dimas committed
292
293
294
295
296
297
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

298
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
299
300
301
302
303
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

    except:

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