Skip to content

Commit

Permalink
Tutorial DONE
Browse files Browse the repository at this point in the history
  • Loading branch information
rakbidb committed Oct 13, 2023
1 parent aaf5b93 commit 91d7d68
Show file tree
Hide file tree
Showing 6 changed files with 240 additions and 48 deletions.
28 changes: 15 additions & 13 deletions main/templates/create_product.html
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
{% extends 'base.html' %}

{% block content %}
<h1>Add New Product</h1>
<div>
<h1>Add New Product</h1>

<form method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
<tr>
<td></td>
<td>
<input type="submit" value="Add Product"/>
</td>
</tr>
</table>
</form>
<form method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
<tr>
<td></td>
<td>
<input type="submit" value="Add Product"/>
</td>
</tr>
</table>
</form>
</div>

{% endblock %}
22 changes: 22 additions & 0 deletions main/templates/edit_product.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{% extends 'base.html' %}

{% load static %}

{% block content %}
<div>
<h1>Edit Product</h1>

<form method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
<tr>
<td></td>
<td>
<input type="submit" value="Edit Product"/>
</td>
</tr>
</table>
</form>
</div>
{% endblock %}
143 changes: 127 additions & 16 deletions main/templates/main.html
Original file line number Diff line number Diff line change
@@ -1,47 +1,158 @@
{% extends 'base.html' %}

{% block content %}
<h1>Shopping List Page</h1>
<nav class="navbar navbar-expand-lg navbar-light bg-light" style="padding: 15px;">
<a class="navbar-brand" href="#">Shopping List Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse d-flex justify-content-end" id="navbarText">
<span class="nav-item">
<a class="nav-link" href="{% url 'main:logout' %}">
<button class="btn btn-sm btn-outline-danger me-2" type="button">
Logout
</button>
</a>
</span>
<span class="navbar-text">
Sesi terakhir login: {{ last_login }}
</span>
</div>
</nav>

<h5>Name:</h5>
<p>{{name}}</p>
<div>
<h1 class="text-center">Shopping List Page</h1>

<h5>Class:</h5>
<p>{{class}}</p>
<h5>Name: {{name}}</h5>
<h5>Class: {{class}}</h5>
<br>

<table>
<table class="table table-bordered text-center" id="product_table">
<tr>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Date Added</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Description</th>
<th scope="col">Date Added</th>
<th scope="col">Edit Something</th>
</tr>

{% comment %} Berikut cara memperlihatkan data produk di bawah baris ini {% endcomment %}

{% for product in products %}
<tr>
<td>{{product.name}}</td>
<td scope="row">{{product.name}}</td>
<td>{{product.price}}</td>
<td>{{product.description}}</td>
<td>{{product.date_added}}</td>
<td>
<a href="{% url 'main:edit_product' product.pk %}">
<button type="button" class="btn btn-primary">
Edit
</button>
</a>
<a href="{% url 'main:delete_product' product.pk %}">
<button type="button" class="btn btn-danger">
Delete
</button>
</a>
</td>
</tr>
{% endfor %}
</table>

<br />
<br>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Add New Product</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="form" onsubmit="return false;">
{% csrf_token %}
<div class="mb-3">
<label for="name" class="col-form-label">Name:</label>
<input type="text" class="form-control" id="name" name="name"></input>
</div>
<div class="mb-3">
<label for="price" class="col-form-label">Price:</label>
<input type="number" class="form-control" id="price" name="price"></input>
</div>
<div class="mb-3">
<label for="description" class="col-form-label">Description:</label>
<textarea class="form-control" id="description" name="description"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="button_add" data-bs-dismiss="modal">Add Product</button>
</div>
</div>
</div>
</div>

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Add Product by AJAX
</button>

<a href="{% url 'main:create_product' %}">
<button>
<button type="button" class="btn btn-success">
Add New Product
</button>
</a>

<a href="{% url 'main:logout' %}">
<h5>Sesi terakhir login: {{ last_login }}</h5>
<button>
<button type="button" class="btn btn-danger">
Logout
</button>
</a>
<br><br>

<p class="text-right">Sesi terakhir login: {{last_login}}</p>
</div>

<script>
async function getProducts() {
return fetch("{% url 'main:get_product_json' %}").then((res) => res.json())
}

async function refreshProducts() {
document.getElementById("product_table").innerHTML = ""
const products = await getProducts()
let htmlString = `<tr>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Date Added</th>
</tr>`
products.forEach((item) => {
htmlString += `\n<tr>
<td>${item.fields.name}</td>
<td>${item.fields.price}</td>
<td>${item.fields.description}</td>
<td>${item.fields.date_added}</td>
</tr>`
})

document.getElementById("product_table").innerHTML = htmlString
}

refreshProducts()

function addProduct() {
fetch("{% url 'main:add_product_ajax' %}", {
method: "POST",
body: new FormData(document.querySelector('#form'))
}).then(refreshProducts)

document.getElementById("form").reset()
return false
}

document.getElementById("button_add").onclick = addProduct
</script>

{% endblock content %}
11 changes: 7 additions & 4 deletions main/urls.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
from django.urls import path
from main.views import show_main, create_product, show_xml, show_json, show_xml_by_id, show_json_by_id, register, login_user, logout_user

from main.views import show_main, create_product, show_xml, show_json, show_xml_by_id, show_json_by_id, register, login_user, logout_user, edit_product, delete_product, get_product_json, add_product_ajax
app_name = 'main'

urlpatterns = [
path('', show_main, name='show_main'),
path('create-product', create_product, name='create_product'),
path('xml/', show_xml, name='show_xml'),
path('xml/', show_xml, name='show_xml'),
path('json/', show_json, name='show_json'),
path('xml/<int:id>/', show_xml_by_id, name='show_xml_by_id'),
path('json/<int:id>/', show_json_by_id, name='show_json_by_id'),
path('json/<int:id>/', show_json_by_id, name='show_json_by_id'),
path('register/', register, name='register'),
path('login/', login_user, name='login'),
path('logout/', logout_user, name='logout'),
path('edit-product/<int:id>', edit_product, name='edit_product'),
path('delete/<int:id>', delete_product, name='delete_product'),
path('get-product/', get_product_json, name='get_product_json'),
path('create-product-ajax/', add_product_ajax, name='add_product_ajax')
]
65 changes: 55 additions & 10 deletions main/views.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import datetime
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.shortcuts import render, redirect
from django.shortcuts import render
from django.http import HttpResponseRedirect
from main.forms import ProductForm
from django.urls import reverse
from main.models import Product
from django.http import HttpResponse
from .models import Product
from django.http import HttpResponse, HttpResponseNotFound
from django.core import serializers
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
import datetime
from django.views.decorators.csrf import csrf_exempt

@login_required(login_url='/login')
def show_main(request):
products = Product.objects.filter(user=request.user)

context = {
'name': request.user.username,
'class': 'PBP A', # Kelas PBP kamu
'class': 'PBP A',
'products': products,
'last_login': request.COOKIES['last_login'],
}
Expand Down Expand Up @@ -83,4 +85,47 @@ def logout_user(request):
logout(request)
response = HttpResponseRedirect(reverse('main:login'))
response.delete_cookie('last_login')
return response
return response

def edit_product(request, id):
# Get product berdasarkan ID
product = Product.objects.get(pk = id)

# Set product sebagai instance dari form
form = ProductForm(request.POST or None, instance=product)

if form.is_valid() and request.method == "POST":
# Simpan form dan kembali ke halaman awal
form.save()
return HttpResponseRedirect(reverse('main:show_main'))

context = {'form': form}
return render(request, "edit_product.html", context)

def delete_product(request, id):
# Get data berdasarkan ID
product = Product.objects.get(pk = id)
# Hapus data
product.delete()
# Kembali ke halaman awal
return HttpResponseRedirect(reverse('main:show_main'))

def get_product_json(request):
product_item = Product.objects.all()
return HttpResponse(serializers.serialize('json', product_item))

...
@csrf_exempt
def add_product_ajax(request):
if request.method == 'POST':
name = request.POST.get("name")
price = request.POST.get("price")
description = request.POST.get("description")
user = request.user

new_product = Product(name=name, price=price, description=description, user=user)
new_product.save()

return HttpResponse(b"CREATED", status=201)

return HttpResponseNotFound()
19 changes: 14 additions & 5 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
{% block meta %}
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
{% endblock meta %}

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha384-KyZXEAg3QhqLMpG8r+J4jsl5c9zdLKaUk5Ae5f5b1bw6AUn5f5v8FZJoMxm6f5cH1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>

<style>
body > div {
margin: 25px;
}
</style>

</head>

<body>
Expand Down

0 comments on commit 91d7d68

Please sign in to comment.