Skip to content

Commit

Permalink
selesai tahapan tutorial 3
Browse files Browse the repository at this point in the history
  • Loading branch information
fathonidf committed Sep 20, 2023
1 parent 069d462 commit 52b196d
Show file tree
Hide file tree
Showing 8 changed files with 186 additions and 5 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,3 +457,27 @@ urlpatterns = [
### 5. JSON by ID
![jsonbyid](https://github.com/fathonidf/adventurers-inventory/assets/105644250/9ae03290-57ea-4acc-9d1c-e012056b60ca)
</details>

---

# Tugas 4

<details>
<summary>1. Apa itu Django UserCreationForm, dan jelaskan apa kelebihan dan kekurangannya?</summary>
</details>

<details>
<summary>2. Apa perbedaan antara autentikasi dan otorisasi dalam konteks Django, dan mengapa keduanya penting?</summary>
</details>

<details>
<summary>3. Apa itu cookies dalam konteks aplikasi web, dan bagaimana Django menggunakan cookies untuk mengelola data sesi pengguna?</summary>
</details>

<details>
<summary>4. Apakah penggunaan cookies aman secara default dalam pengembangan web, atau apakah ada risiko potensial yang harus diwaspadai?</summary>
</details>

<details>
<summary>5. Jelaskan bagaimana cara kamu mengimplementasikan checklist di atas secara step-by-step (bukan hanya sekadar mengikuti tutorial).</summary>
</details>
22 changes: 22 additions & 0 deletions main/migrations/0003_item_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 4.2.4 on 2023-09-20 08:43

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('main', '0002_item_delete_weapon'),
]

operations = [
migrations.AddField(
model_name='item',
name='user',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
2 changes: 2 additions & 0 deletions main/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from django.db import models
from django.contrib.auth.models import User


class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
amount = models.IntegerField()
description = models.TextField()
Expand Down
45 changes: 45 additions & 0 deletions main/templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{% extends 'base.html' %}

{% block meta %}
<title>Login</title>
{% endblock meta %}

{% block content %}

<div class = "login">

<h1>Login</h1>

<form method="POST" action="">
{% csrf_token %}
<table>
<tr>
<td>Username: </td>
<td><input type="text" name="username" placeholder="Username" class="form-control"></td>
</tr>

<tr>
<td>Password: </td>
<td><input type="password" name="password" placeholder="Password" class="form-control"></td>
</tr>

<tr>
<td></td>
<td><input class="btn login_btn" type="submit" value="Login"></td>
</tr>
</table>
</form>

{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

Don't have an account yet? <a href="{% url 'main:register' %}">Register Now</a>

</div>

{% endblock content %}
8 changes: 8 additions & 0 deletions main/templates/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,18 @@ <h3>Total items in your inventory : {{total_items}}</h3>

<br />

<h5>Sesi terakhir login: {{ last_login }}</h5>

<a href="{% url 'main:create_item' %}">
<button>
Add New Item
</button>
</a>

<a href="{% url 'main:logout' %}">
<button>
Logout
</button>
</a>

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

{% block meta %}
<title>Register</title>
{% endblock meta %}

{% block content %}

<div class = "login">

<h1>Register</h1>

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

{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

</div>

{% endblock content %}
5 changes: 4 additions & 1 deletion main/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from django.urls import path, include
from main.views import show_main, create_item, show_xml, show_json, show_xml_by_id, show_json_by_id
from main.views import show_main, create_item, show_xml, show_json, show_xml_by_id, show_json_by_id, register, login_user, logout_user


app_name = 'main'

urlpatterns = [
path('', show_main, name='show_main'),
path('create-item', create_item, name='create_item'),
path('register/', register, name='register'),
path('login/', login_user, name='login'),
path('logout/', logout_user, name='logout'),
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'),
Expand Down
51 changes: 47 additions & 4 deletions main/views.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
import datetime
from django.shortcuts import render
from django.http import HttpResponseRedirect
from main.forms import ItemForm
from django.urls import reverse
from main.models import Item
from django.http import HttpResponse
from django.core import serializers
from django.shortcuts import redirect #tutor 3
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

# Create your views here.
@login_required(login_url='/login')
def show_main(request):
items = Item.objects.all()
items = Item.objects.filter(user=request.user)
total_items = items.count()

context = {
'app_name': 'Adventurer\'s Inventory',
'name': 'Daffa Mohamad Fathoni',
'name': request.user.username,
'class': 'PBP E',
'total_items': total_items,
'items': items
'items': items,
'last_login': request.COOKIES['last_login']
}

return render(request, "main.html", context)
Expand All @@ -25,12 +33,47 @@ def create_item(request):
form = ItemForm(request.POST or None)

if form.is_valid() and request.method == "POST":
form.save()
item = form.save(commit=False)
item.user = request.user
item.save()
return HttpResponseRedirect(reverse('main:show_main'))

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

def register(request):
form = UserCreationForm()

if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Your account has been successfully created!')
return redirect('main:login')
context = {'form':form}
return render(request, 'register.html', context)

def login_user(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
response = HttpResponseRedirect(reverse("main:show_main"))
response.set_cookie('last_login', str(datetime.datetime.now()))
return response
else:
messages.info(request, 'Sorry, incorrect username or password. Please try again.')
context = {}
return render(request, 'login.html', context)

def logout_user(request):
logout(request)
response = HttpResponseRedirect(reverse('main:login'))
response.delete_cookie('last_login')
return response

def show_xml(request):
data = Item.objects.all()
return HttpResponse(serializers.serialize("xml", data), content_type="application/xml")
Expand Down

0 comments on commit 52b196d

Please sign in to comment.