Reputation: 51
I am trying to create a form which will allow users to input data into my database. I have followed many tutorials which may have lead to my confusion. The problem is that my page is showing up with all the html elements, but the form is not being displayed. I have no idea why. Can anyone please help? Thanks!
Here is my code:
#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
Upvotes: 0
Views: 1859
Reputation: 34553
You're not passing the form to the template if the request is a GET. There's really no need to distinguish between the GET and POST in this case when creating the form instance. You can simply instantiate your form as such:
form = BlockForm(request.POST or None)
and drop the instantiation after the if request.POST
. I'm also not sure why you're using render_to_response
if it's a POST vs render
on the GET. You can use render
in both cases.
Your view really only needs to be:
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})
Upvotes: 3