Skip to content
Advertisement

Django Rendering Form in HTML Issue

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)

webpage

This is the code for the form in question.

forms.py

from django import forms
from django.forms import ChoiceField, ModelForm, RadioSelect
from .models import command_node
from .models import beacon


class Command_Form(ModelForm):
    class Meta:
        model = command_node
        fields = (
            'host_id',
            'current_commands'
        )
        
        host_id = forms.ModelChoiceField(
            required=True,
            queryset=beacon.objects.all(),
            widget=forms.Select(
                attrs={
                    'class': 'form-control'
                },
            )
        )

        current_comamnds = forms.ChoiceField(
            required=True,

            choices=[
                ('Sleep', "Sleep"),
                ('Open SSH_Tunnel', 'Open SSH_Tunnel'),
                ('Close SSH_Tunnel', 'Close SSH_Tunnel'),
                ('Open TCP_Tunnel', 'Open TCP_Tunnel'),
                ('Close TCP_Tunnel', 'Close TCP_Tunnel'),
                ('Open Dynamic', 'Open Dynamic'),
                ('Close Dynamic', 'Close Dynamic'),
                ('Task', 'Task'),
            ])

This is the html in question. I’ve removed non-relevant segments

home.html

</br>
</br>
    <form action="" method=POST>
        {% csrf_token %}
        {{ form }}
        <button type="Submit" class="btn btn-secondary btn-sm">Submit</button>
    </form>
</body>
</html>

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

from django.shortcuts import render
from django.http import HttpResponse
from .models import beacon
from .models import command_node
from .forms import Command_Form
from django.http import HttpResponseRedirect

def home(request):
    form = Command_Form,
    if request.method == "POST":
            form = form(request.POST)
            if form.is_valid():
                form.save()
                return render(request, 'home.html', {"form": form})

    return render(request, 'home.html', {"form": form},)

Advertisement

Answer

Try:

form = Command_Form()
if request.method == "POST":
    form = Command_Form(request.POST)

I believe you are not instantiating the model and that’s the problem.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement