我正在尝试创建一个允许用户将数据输入我的数据库的表单。我遵循了许多可能导致我混淆的教程。问题是我的页面显示所有的html元素,但表单没有显示。我不知道为什么。有人可以帮忙吗?谢谢!
这是我的代码:
#forms for blocks
from django import forms
from .models import Block
class BlockForm(forms.ModelForm):
class Meta:
model = Block
fields = ['block_status', 'block_name', 'block_derivatives', 'block_subsystems', 'owners']
# def requests view.py
def requests(request, inventory_id):
inventory = get_object_or_404(Inventory, pk=inventory_id)
#return render(request, 'inventory/requests.html', {'inventory': inventory})
form = BlockForm()
if request.POST:
form = BlockForm(request.POST)
if form.is_valid():
form.save()
print"FUFUFUFUFUF"
return HttpResponseRedirect('/inventory/2')
else:
form = BlockForm()
print "LOLOLO"
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('requests.html', args)
print "HIHIHIHIHIH"
return render(request, 'inventory/requests.html', {'inventory': inventory})
# urls
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<inventory_id>.*)/$', views.detail, name='detail'),
url(r'^(?P<inventory_id>[0-9]+)/requests$', views.requests, name='requests'),
#url(r'^(?P<inventory_id>.*)block_form/$', views.block_form)
]
#requests.html
<div class="blockform">
<div class="container">
<form action="{% url 'inventory:requests' inventory.id %}" method="post">{% csrf_token %}
<ul>
<li>Hello, world.</li>
{{form.as_table}}
</ul>
<input type="submit" name="submit" value="Request Blocks">
</form>
</div>
</div>
enter code here
答案 0 :(得分:3)
如果请求是GET,则表示您没有将表单传递给模板。在创建表单实例时,实际上没有必要区分GET和POST。您可以简单地实例化您的表单:
form = BlockForm(request.POST or None)
并删除if request.POST
之后的实例化。我也不确定为什么你使用render_to_response
,如果它是GET上的POST与render
。在这两种情况下都可以使用render
。
您的观点实际上只需要:
def requests(request, inventory_id):
inventory = get_object_or_404(Inventory, pk=inventory_id)
form = BlockForm(request.POST or None)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect('/inventory/2')
return render(request, 'inventory/requests.html',
{'inventory': inventory, 'form': form})