Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Form Submit Button

I have a pretty simple file upload form class in django:

class UploadFileForm(forms.Form):
    category = forms.ChoiceField(get_category_list())
    file = forms.FileField()

one problem is that when i do {{ form.as_p }}, It has no submit button. How do i add one?

like image 824
The.Anti.9 Avatar asked Jan 17 '10 07:01

The.Anti.9


2 Answers

<input type="submit" value="Gogogo!" />
like image 117
Ignacio Vazquez-Abrams Avatar answered Oct 30 '22 03:10

Ignacio Vazquez-Abrams


This is a template for a minimal HTML form (docs):

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form>

Put that under <PROJECT>/templates/MyForm.html and then replace 'DIRS': [] in <PROJECT>/<PROJECT>/settings.py with the following:

        'DIRS': [os.path.join(BASE_DIR, "templates")],

Code like this can then be used to serve your form to the user when he does a GET request, and process the form when he POSTs it by clicking on the submit button (docs):

from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render
from . import forms

def my_form(request):
    if request.method == 'POST':
        form = forms.MyForm(request.POST)
        if form.is_valid():
            return HttpResponse('Yay valid')
    else:
        form = forms.MyForm()

    return render(request, 'MyForm.html', {'form': form})
like image 5
xjcl Avatar answered Oct 30 '22 03:10

xjcl