I’m attempting to render a form, in html and have tried the normal {{ form }}. However when I go to the site set up by: python manage.py runserver. I get the following where the form should go (highlighted section on screen-capture)
This is the code for the form in question.
forms.py
JavaScript
x
38
38
1
from django import forms
2
from django.forms import ChoiceField, ModelForm, RadioSelect
3
from .models import command_node
4
from .models import beacon
5
6
7
class Command_Form(ModelForm):
8
class Meta:
9
model = command_node
10
fields = (
11
'host_id',
12
'current_commands'
13
)
14
15
host_id = forms.ModelChoiceField(
16
required=True,
17
queryset=beacon.objects.all(),
18
widget=forms.Select(
19
attrs={
20
'class': 'form-control'
21
},
22
)
23
)
24
25
current_comamnds = forms.ChoiceField(
26
required=True,
27
28
choices=[
29
('Sleep', "Sleep"),
30
('Open SSH_Tunnel', 'Open SSH_Tunnel'),
31
('Close SSH_Tunnel', 'Close SSH_Tunnel'),
32
('Open TCP_Tunnel', 'Open TCP_Tunnel'),
33
('Close TCP_Tunnel', 'Close TCP_Tunnel'),
34
('Open Dynamic', 'Open Dynamic'),
35
('Close Dynamic', 'Close Dynamic'),
36
('Task', 'Task'),
37
])
38
This is the html in question. I’ve removed non-relevant segments
home.html
JavaScript
1
10
10
1
</br>
2
</br>
3
<form action="" method=POST>
4
{% csrf_token %}
5
{{ form }}
6
<button type="Submit" class="btn btn-secondary btn-sm">Submit</button>
7
</form>
8
</body>
9
</html>
10
Lastly I’ve included the views as I suspect it might have something to do with it but I’m not certain. I’m trying to make it so that when the form is submitted the page is reloaded.
Views.py
JavaScript
1
17
17
1
from django.shortcuts import render
2
from django.http import HttpResponse
3
from .models import beacon
4
from .models import command_node
5
from .forms import Command_Form
6
from django.http import HttpResponseRedirect
7
8
def home(request):
9
form = Command_Form,
10
if request.method == "POST":
11
form = form(request.POST)
12
if form.is_valid():
13
form.save()
14
return render(request, 'home.html', {"form": form})
15
16
return render(request, 'home.html', {"form": form},)
17
Advertisement
Answer
Try:
JavaScript
1
4
1
form = Command_Form()
2
if request.method == "POST":
3
form = Command_Form(request.POST)
4
I believe you are not instantiating the model and that’s the problem.