p.ry
p.ry

Reputation: 489

How do i add <input type="button"> as a formfield in django

I want to have an input field as a button in my template. Just like this.I am manually rendering form fields in my template.So, how do i create a field like that in my form.

Formfield in forms.py

class DetailForm(forms.Form):
    owner=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

views.py 

def getDetail(request):
   form=DetailForm()
   return render(request,'materials/addpage.html',{'form':form})

and template,

<div class="form-group">
 {{form.owner}}
</div>

Upvotes: 5

Views: 21146

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77261

A minimal example of using buttons as input in Django looks like this:

Template:

<form method="POST">
 {% csrf_token %}
 <input type="submit" name="btn" value="yes">
 <input type="submit" name="btn" value="no">
</form>
{{ val }}

Form:

class Fooform(forms.Form):
    btn = forms.CharField()

View:

def test_view(request):
    if request.method == 'POST':
        form = Fooform(request.POST)
        if form.is_valid():
            val = form.cleaned_data.get("btn")
    else:
        form = Fooform()
    return render(request, 'template.html', locals())

Libraries like crispy-forms have button widgets.

Upvotes: 15

Related Questions