Rachel
Rachel

Reputation: 247

Django Process Form data in views.py on submit

I Want to process my form data and view and update my mongo DB if name not present else if name present update the DB. Before that, I want to make sure if the entire subject is proper.. using some regex.

But when I add name and subject in below form code nothing is happening. How do I get the form data in view and do the proper check? And where should I do the input validation in views or form.html ??

if entered data is not proper format throw error? how can I do this?

form_template.html

<div class="container">
<div class="col-md-5">
    <div class="form-area">
        <form id="add-form" method="POST" action="{% url 'myapp:add_data' %}" role="form">
        <br style="clear:both">
                    <h4 style="margin-bottom: 25px; text-align: center;"> New Data</h3>
                                <div class="form-group">
                                                <input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
                                        </div>
                                        <div class="form-group">
                                                <input type="text" class="form-control" id="sub_list" name="sub_list" placeholder="Sub List comma separated" required>
                                        </div>
                                         <button type="button" id="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
        </form>
    </div>
    </div>
</div>
</div>

myapp/url.py

url(r'^new_data$', views.add_data, name='add_data'),

And below is my view function

def add_data(request):
    print "Herfe"
    if request.POST:
        print "coming here"
        I want validate user entered input is proper
        messages.success(request, 'Form submission successful')
        return render(request, '/index.html')

Upvotes: 1

Views: 3853

Answers (1)

Vineeth Sai
Vineeth Sai

Reputation: 3447

you can use request.POST.get(<name>) to get the data from the template and then preprocess it.

So in your case it simply becomes

def add_data(request):
    print "Herfe"
    if request.POST:
        print "coming here"
        data = request.POST.get('name')
        # now validate to your heart's content
        messages.success(request, 'Form submission successful')
        return render(request, '/index.html')

On a side note I think you are missing out the benefits of forms in django. If you use the forms API properly you can easily pass values and validate them with inbuilt methods. In that case it would become

form = YourForm(request.POST)
if form.is_valid():
    form.save()
    your_variable = form.cleaned_data['name'] # validates for malicious data automatically
    # Now you can do further validations accordingly.

Upvotes: 2

Related Questions