Fakultas Ilmu Komputer UI

Commit 2a2d83dd authored by Rayza Arasj Mahardhika's avatar Rayza Arasj Mahardhika
Browse files

Redirect after POST, and show all items in template

parent d171fa9c
Pipeline #21003 failed with stage
in 3 minutes and 5 seconds
# Generated by Django 2.2.5 on 2019-09-25 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
]
# Generated by Django 2.2.5 on 2019-09-25 15:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lists', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='item',
name='text',
field=models.TextField(default=''),
),
]
......@@ -10,7 +10,9 @@
</form>
<table id="id_list_table">
<tr><td>1: {{ new_item_text }}</td></tr>
{% for item in items %}
<tr><td>{{ forloop.counter }}: {{ item.text }}</td></tr>
{% endfor %}
</table>
</body>
</html>
......@@ -16,9 +16,30 @@ class HomePageTest(TestCase):
self.assertTemplateUsed(response, 'home.html')
def test_can_save_a_POST_request(self):
self.client.post('/', data={'item_text': 'A new list item'})
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new list item')
def test_redirects_after_POST(self):
response = self.client.post('/', data={'item_text': 'A new list item'})
self.assertIn('A new list item', response.content.decode())
self.assertTemplateUsed(response, 'home.html')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['location'], '/')
def test_only_saves_items_when_necessary(self):
self.client.get('/')
self.assertEqual(Item.objects.count(), 0)
def test_displays_all_list_items(self):
Item.objects.create(text='itemey 1')
Item.objects.create(text='itemey 2')
response = self.client.get('/')
self.assertIn('itemey 1', response.content.decode())
self.assertIn('itemey 2', response.content.decode())
class AboutPageTest(TestCase):
......
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect, render
from lists.models import Item
def home_page(request):
return render(request, 'home.html', {
'new_item_text': request.POST.get('item_text', ''),
})
if request.method == 'POST':
Item.objects.create(text=request.POST['item_text'])
return redirect('/')
items = Item.objects.all()
return render(request, 'home.html', {'items': items})
def about_page(request):
return HttpResponse(
......
Supports Markdown
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