Reputation: 365
I have two template in django:
first, i give name index.html
<html>
<head>
<title>Django</title>
</head>
<body>
<div id="formulir">
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="label">Username</div><div class="input"><input type="text" name="username"/></div>
<div class="label">Email</div><div class="input"><input type="text" name="email"/></div>
<input type="submit" name="tambah" value="Add"/>
</form>
</div>
<div id="data">
{% block data %}{% endblock %}
</div>
</body>
</html>
Second, i give name data.html
{% extends 'index.html' %}
{% block data %}
<table border="1">
<tr>
<th>Username</th>
<th>Email</th>
</tr>
{% for i in data %}
<tr>{{ i.username }}</tr>
<tr>{{ i.email }}</tr>
{% endfor %}
</table>
{% endblock %}
I want to do when form in index.html submitted, the data show in data.html and when I submitted for the second time the data.html show 2 data, so the first data still exist. I don't want to save the data to database.
This is my views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
global data
data = []
def home(request):
if request.POST:
data = data.append(request.POST)
return render_to_response('data.html', locals(), context_instance=RequestContext(request))
return render_to_response('index.html', locals(), context_instance=RequestContext(request))
anybody can help me?
Upvotes: 2
Views: 6476
Reputation: 22561
Using global variables is bad practice overall but you may use it if your application run with one system process: Python Django Global Variables. You can save data in session or you need to put all posted data to form and repost it in hidden inputs for example if you need to get it without saving anywhere:
...
<div id="formulir">
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="label">Username</div><div class="input"><input type="text" name="username"/></div>
<div class="label">Email</div><div class="input"><input type="text" name="email"/></div>
<input type="submit" name="tambah" value="Add"/>
{% for i in data %}
<input type="hidden" name="username" value="{{ i.username }}"/>
<input type="hidden" name="email" value="{{ i.email }}"/>
{% endfor %}
</form>
</div>
....
To create data
variable and access to it in templates with code like that {{ i.username }}
you need some logic in view:
def home(request):
data = []
if request.POST:
username = request.POST.getlist('username')
email = request.POST.getlist('email')
data = [{'username': u, 'email': e} for u, e in zip(username, email)]
return render_to_response('data.html', locals(),
context_instance=RequestContext(request))
return render_to_response('index.html', locals(),
context_instance=RequestContext(request))
Upvotes: 3