Commit 3d032a66 authored by Tarsvini's avatar Tarsvini

update lab_7

parent 09b1241d
Pipeline #14660032 passed with stages
in 4 minutes and 28 seconds
No preview for this file type
......@@ -49,10 +49,6 @@ class CSUIhelper:
mahasiswa_list = response.json()["results"]
return mahasiswa_list
def get_data_api(self, page):
response = requests.get(API_MAHASISWA_LIST_URL,
params={"access_token": self.access_token, "client_id": self.client_id, "page": page})
return response
......
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-12-03 03:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lab_7', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='friend',
name='alamat',
field=models.CharField(default='-', max_length=400),
),
migrations.AddField(
model_name='friend',
name='prodi',
field=models.CharField(default='-', max_length=100),
),
migrations.AddField(
model_name='friend',
name='ttl',
field=models.CharField(default='-', max_length=400),
),
]
from __future__ import unicode_literals
#rom __future__ import unicode_literals
from django.db import models
class Friend(models.Model):
friend_name = models.CharField(max_length=400)
npm = models.CharField(max_length=250, unique=True)
alamat = models.CharField(max_length=400, default="-")
ttl = models.CharField(max_length=400, default="-")
prodi = models.CharField(max_length=100, default="-")
added_at = models.DateField(auto_now_add=True)
def as_dict(self):
return {
"friend_name": self.friend_name,
"npm": self.npm,
}
# def as_dict(self):
# return {
# "friend_name": self.friend_name,
# "npm": self.npm,
# }
\ No newline at end of file
{% extends "lab_7/layout/base.html" %}
{% block content %}
<section name="friend-list" id="friend-list">
<section name="friend-list" class="friend-list">
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-8">
<h2> friend Fasilkom</h2>
<h2>Fasilkom Friends</h2>
<div id="friend-list" class="list-group">
</div>
</div>
</div>
......@@ -17,18 +16,51 @@
{% block javascript %}
<script>
$( document ).ready(function () {
{# fill this ajax call to retrieve the friend list on database #}
// {# lengkapi pemanggilan ajax berikut untuk mengambil daftar teman yang ada di database #}
$.ajax({
method: "GET",
url: "{% url 'lab-7:get-friend-list' %}", // update
success: function (response) {
#Show friend lists to the page
#hint : use jquery append() function
},
error: function(error){
#show error message
url: '{% url "lab-7:get-friend-list" %}',//#URL untuk mendapatkan list teman,
success: function (friend_list) {
console.log(friend_list)
var list = JSON.parse(friend_list);
// #tampilkan list teman ke halaman
// #hint : gunakan fungsi jquery append()
if(list.length==0) {
var html = '<div class="alert alert-danger text-center">\
<strong>Oops!</strong> Tidak ada teman\
</div>';
$("#friend-list").append(html)
}
else {
$.each(list, function(index, friend) {
var button = '<span class="pull-right">'+
'<button type="button" class="btn btn-xs btn-danger"'+
'onClick="deleteFriend('+friend.fields.npm+')">'+
'&times;'+
'</button>'+
'</span>';
var detail = '<span class="col-xs-4 col-md-2 pull-right">'+
'<button type="button" class="btn btn-xs btn-default btn-block"'+
'onClick="description('+friend.fields.npm+')">'+
'detail'+
'</button>'+
'</span>';
var html = '<a class="list-group-item clearfix">'+
friend.fields.friend_name +
' (' + friend.fields.npm + ')' + button + detail + '</a>';
$("#friend-list").append(html)
});
}
}
});
});
const deleteFriend = function(npm) {
window.open('delete-friend/'+npm+'/', '_self');
}
const description = function(npm) {
window.open('description/'+npm+'/', '_self');
}
</script>
{% endblock %}
{% extends "lab_7/layout/base.html" %}
{% block content %}
<section name="friend-list" class="friend-list">
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-12">
<h2>{{ friend.friend_name }} </h2>
</div>
<div class="col-md-8 col-lg-12">
<table width="100%">
<tr>
<td><h4>NPM</h4></td>
<td><h4>{{ friend.npm }}</h4></td>
</tr>
<tr>
<td><h4>Prodi</h4></td>
<td><h4>{{ friend.prodi }}</h4></td>
</tr>
<tr>
<td><h4>TTL</h4>
<td><h4>{{ friend.ttl }}</h4></td>
</tr>
<tr>
<td><h4>Alamat</h4></td>
<td><h4 id="address">{{ friend.alamat }}</h4></td>
</tr>
</table>
</div>
</div>
</div>
<div class="container">
<div id="googleMap" style="width:300px; height:200px; margin: 50px 0"></div>
</div>
<div>
</div>
</section>
{% endblock %}
{% block javascript %}
<script>
console.log($("#address").text());
var address = $("#address").text();
function initMap() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var propertiPeta = {
center: results[0].geometry.location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var peta = new google.maps.Map(document.getElementById("googleMap"), propertiPeta);
var marker = new google.maps.Marker({
map: peta,
position: results[0].geometry.location
});
} else {
var html = '<div class="alert alert-danger text-center">\
Lokasi tidak ditemukan!\
</div>';
$("#googleMap").append(html)
}
});
}
</script>
{% endblock %}
......@@ -11,7 +11,7 @@
<a class="list-group-item clearfix">
{{ mahasiswa.nama }} ({{ mahasiswa.npm }})
<span class="pull-right">
<span class="btn btn-xs btn-default" onClick="addFriend('{{ mahasiswa.nama }}', '{{ mahasiswa.npm }}')">
<span class="btn btn-xs btn-default" onClick="addFriend('{{ mahasiswa.nama }}', '{{ mahasiswa.npm }}', '{{ mahasiswa.alamat_mhs }}', '{{ mahasiswa.kota_lahir }}, {{ mahasiswa.tgl_lahir }}', '{{ mahasiswa.program.0.nm_org }} ({{ mahasiswa.program.0.nm_prg }})')">
Tambah sebagai teman
</span>
</span>
......@@ -19,10 +19,37 @@
{% endfor %}
{% else %}
<div class="alert alert-danger text-center">
<strong>Opps!</strong> Tidak ada mahasiswa
<strong>Oops!</strong> Tidak ada mahasiswa
</div>
{% endif %}
{% if mahasiswa_list.has_other_pages %}
<ul class="pagination">
{% if mahasiswa_list.has_previous %}
<li><a href="{% url 'lab-7:index' %}">&laquo;</a></li>
<li><a href="?page={{ mahasiswa_list.previous_page_number }}">&lsaquo;</a></li>
{% else %}
<li class="disabled"><span>&lsaquo;</span></li>
{% endif %}
{% for page in page_range %}
{% if mahasiswa_list.number == page %}
<li class="active"><span>{{ page }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li><a href="?page={{ page }}">{{ page }}</a></li>
{% endif %}
{% endfor %}
{% if mahasiswa_list.has_next %}
<li><a href="?page={{ mahasiswa_list.next_page_number }}">&rsaquo;</a></li>
<li><a href="?page={{ mahasiswa_list.paginator.num_pages }}">&raquo;</a></li>
{% else %}
<li class="disabled"><span>&rsaquo;</span></li>
{% endif %}
</ul>
{% endif %}
</div>
{% if auth %}
<div id="token" hidden="true">{{ auth.access_token }}</div>
<div id="cid" hidden="true">{{ auth.client_id }}</div>
{% endif %}
</div>
<div class="col-lg-4">
<h2> Teman Saya </h2>
......@@ -35,15 +62,15 @@
{% endfor %}
{% else %}
<div class="alert alert-danger text-center">
<strong>Opps!</strong> Tidak ada teman
<strong>Oops!</strong> Tidak ada teman
</div>
{% endif %}
</div>
<form id="add-friend" action="#">
{% csrf_token %}
<label for="field_npm">npm</label>
<label for="field_npm">NPM:</label>
<input id="field_npm" type="text" name="npm" class="form-control"/>
<label for="field_name">name</label>
<label for="field_name">Name:</label>
<input id="field_name" type="text" name="name" class="form-control"/>
<button type="submit">Tambah</button>
</form>
......@@ -54,27 +81,43 @@
{% endblock %}
{% block javascript %}
<script>
var addFriend = function(nama, npm) {
var token = document.getElementById("token").innerHTML;
var cid = document.getElementById("cid").innerHTML;
var addFriend = function(nama, npm, alamat, ttl, prodi) {
$.ajax({
method: "POST",
url: "{% url "lab-7:add-friend" %}",
data: { name: nama, npm: npm},
url: '{% url "lab-7:add-friend" %}',
data: { name: nama, npm: npm, alamat: alamat, ttl: ttl, prodi: prodi},
success : function (friend) {
html = '<a class="list-group-item clearfix">' +
friend.friend_name +
'</a>';
nama + ' (' + npm +')</a>';
$("#friend-list").append(html)
},
error : function (error) {
alert(error.responseText)
alert("Mahasiswa tersebut sudah ditambahkan sebagai teman")
}
});
};
$("#add-friend").on("submit", function () {
name = $("#field_name").val()
npm = $("#field_npm").val()
addFriend(name, npm)
$("#add-friend").on("submit", function (event) {
var npm = $("#field_npm").val();
var corsProxy = 'https://cors-anywhere.herokuapp.com/';
var obj = new Object(); obj.access_token = token; obj.client_id = cid;
var param = $.param(obj);
$.ajax({
method: "GET",
url: corsProxy+'https://api-dev.cs.ui.ac.id/siakngcs/mahasiswa/'+npm+'/?'+param,
success: function(data) {
addFriend(data.nama, data.npm, data.alamat_mhs,
data.kota_lahir+", "+data.tgl_lahir,
data.program[0].nm_org+" ("+data.program[0].nm_prg+")"
)
},
error: function(error) {
console.log(error)
alert("\n\t\t\tNPM tidak valid:\n\n'Tidak ada mahasiswa dengan NPM tersebut'")
}
});
event.preventDefault();
});
......@@ -91,11 +134,10 @@
success: function (data) {
console.log(data)
if (data.is_taken) {
alert("Mahasiswa dengan npm seperti ini sudah ada");
alert("Mahasiswa dengan NPM tersebut sudah menjadi teman");
}
}
});
});
</script>
{% endblock %}
......@@ -35,6 +35,8 @@
<!-- Jquery n Bootstrap Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="application/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Google Map Script -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBnbJQq5rFmTEx43VzVmSLEu4UmPKYhkeI&callback=initMap" async defer>"</script>
{% block javascript %}
{% endblock %}
</body>
......
......@@ -8,12 +8,12 @@
#<span class="icon-bar"></span>
#<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="">Home</a>
<a class="navbar-brand" href="{% url 'lab-7:index' %}">Home</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<!-- LINK INTO table, and link into home#form -->
<li><a href="{% url 'lab-7:get-friend-list' %}#friend-list">Friends</a></li>
<li><a href="{% url 'lab-7:friend-list' %}">Friends</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
......
from django.conf.urls import url
from .views import index, add_friend, friend_list,validate_npm,delete_friend,friend_list_json
from .views import index, add_friend, friend_list,validate_npm,delete_friend,get_friend_list, friend_description
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^add-friend/$', add_friend, name='add-friend'),
url(r'^validate-npm/$', validate_npm, name='validate-npm'),
url(r'^delete-friend/(?P<friend_id>[0-9]+)/$', delete_friend, name='delete-friend'),
url(r'^get-friend-list/$', friend_list_json, name='get-friend-list')
]
url(r'delete-friend/(?P<npm>[0-9]+)/$', delete_friend, name='delete-friend'),
url(r'^friend-list/$', friend_list, name='friend-list'),
url(r'^get-friend-list/$', get_friend_list, name='get-friend-list'),
url(r'description/(?P<npm>[0-9]+)/$', friend_description, name='friend-description')
]
\ No newline at end of file
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Friend
from .api_csui_helper.csui_helper import CSUIhelper
import os
import json
response = {}
csui_helper = CSUIhelper()
def index(request):
# Page halaman menampilkan list mahasiswa yang ada
# TODO berikan akses token dari backend dengan menggunakaan helper yang ada
mahasiswa_list = csui_helper.instance.get_mahasiswa_list()
friend_list = Friend.objects.all()
auth = csui_helper.instance.get_auth_param_dict()
#Paginator
page = request.GET.get('page', 1)
paginate_data = paginate_page(page, mahasiswa_list)
mahasiswa = paginate_data['data']
page_range = paginate_data['page_range']
response = {"mahasiswa_list": mahasiswa, "friend_list": friend_list, "page_range": page_range, "auth": auth}
html = 'lab_7/lab_7.html'
return render(request, html, response)
def paginate_page(page, data_list):
paginator = Paginator(data_list, 10)
try:
data = paginator.page(page)
except PageNotAnInteger:
data = paginator.page(1)
except EmptyPage:
data = paginator.page(paginator.num_pages)
# Get the index of the current page
index = data.number - 1
# This value is maximum index of your pages, so the last page - 1
max_index = len(paginator.page_range)
# You want a range of 10, so lets calculate where to slice the list
start_index = index if index >= 10 else 0
end_index = 10 if index < max_index - 10 else max_index
# Get our new page range. In the latest versions of Django page_range returns
# an iterator. Thus pass it to list, to make our slice possible again.
page_range = list(paginator.page_range)[start_index:end_index]
paginate_data = {'data':data, 'page_range':page_range}
return paginate_data
def friend_list(request):
friend_list = Friend.objects.all()
response['friend_list'] = friend_list
html = 'lab_7/daftar_teman.html'
return render(request, html, response)
def friend_list_json(request): # update
friends = [obj.as_dict() for obj in Friend.objects.all()]
return JsonResponse({"results": friends}, content_type='application/json')
def get_friend_list(request):
if request.method == 'GET':
friend_list = Friend.objects.all()
data = serializers.serialize('json', friend_list)
return HttpResponse(data)
@csrf_exempt
def add_friend(request):
if request.method == 'POST':
name = request.POST['name']
npm = request.POST['npm']
friend = Friend(friend_name=name, npm=npm)
alamat = request.POST['alamat']
ttl = request.POST['ttl']
prodi = request.POST['prodi']
taken = Friend.objects.filter(npm__iexact=npm).exists()
if(not taken):
friend = Friend(friend_name=name, npm=npm, alamat=alamat, ttl=ttl, prodi=prodi)
friend.save()
return JsonResponse(friend.as_dict())
data = model_to_dict(friend)
return HttpResponse(data)
def delete_friend(request, friend_id):
Friend.objects.filter(id=friend_id).delete()
return HttpResponseRedirect('/lab-7/')
def delete_friend(request, npm):
Friend.objects.filter(npm=npm).delete()
return HttpResponseRedirect('/lab-7/friend-list')
@csrf_exempt
def validate_npm(request):
npm = request.POST.get('npm', None)
data = {
'is_taken': Friend.objects.filter(npm=npm).exists()
'is_taken': Friend.objects.filter(npm__iexact=npm).exists() #lakukan pengecekan apakah Friend dgn npm tsb sudah ada
}
return JsonResponse(data)
def friend_description(request, npm):
friend = Friend.objects.filter(npm=npm)[0]
response['friend'] = friend;
html = 'description.html'
return render(request, html, response)
def model_to_dict(obj):
data = serializers.serialize('json', [obj,])
struct = json.loads(data)
data = json.dumps(struct[0]["fields"])
return data
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment