Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I build my form without using Django form?

I'm using Django and I just did a big form Using HTML5 and bootstrap. Can I still send the form via the post method to django if I'm not using it to generate the form? Should I definitely redo my form using Django?

like image 960
mel Avatar asked Sep 07 '25 22:09

mel


1 Answers

NOTE: There may be a better way of doing this, if there is I'd really like to know, this is just how I have done it in the past.

You will still need a forms.py file in your app.

In forms.py:

from django import forms

class MyForm(forms.Form):

    # FORM FIELDS HERE

Then put the form in the context dictionary for your view:

def myView(request):

    if request.method == "POST":

        # FORM PROCESSING HERE

    else:

        myform = MyForm() #create empty form

    return render(request, "template.html", {"myform": myForm}

Now in your template you can add:

        <form id="myForm" name="myFormName" method="post" action=".">
            {% csrf_token %}
            {% for field in myform %}
            {{ field.as_hidden }}
            {% endfor %}
        </form>

This will add your django form to the page without displaying it. All of your form inputs are given the id id_fieldName where fieldName is the field name you defined in the forms.py file.

Now when the user clicks your "submit" button (which I am assuming is a bootstrap button given the rest of your form is). You can use Jquery to input the bootstrap field values into those of the hidden form.

Something like:

$("#mySubmitButton").click(function() {

        $("#id_djangoFormField").val($("#myBootstrapFormField").val());
        $("#myForm").submit();

    }
);

This will submit the django form with the inputs from bootstrap. This can be processed in the view as normal using cleaned_data["fieldName"].

like image 142
RichSmith Avatar answered Sep 09 '25 21:09

RichSmith