Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-Forms with json fields

Tags:

I am looking to accept json data in a form field and than validate it using some database operations. The data will mostly consist of an array of integers. So can you please help me as to how can i do so.

I have tried to google this but didn't get any decent answer. Please help.

like image 762
Saransh Mohapatra Avatar asked Jan 31 '13 13:01

Saransh Mohapatra


2 Answers

You need to take it as text input using CharField. And in the clean method of this field, you can validate it as per your requirement to check if input is valid.

Something like:

class myForm(forms.Form):
     jsonfield = forms.CharField(max_length=1024)

    def clean_jsonfield(self):
         jdata = self.cleaned_data['jsonfield']
         try:
             json_data = json.loads(jdata) #loads string as json
             #validate json_data
         except:
             raise forms.ValidationError("Invalid data in jsonfield")
         #if json data not valid:
            #raise forms.ValidationError("Invalid data in jsonfield")
         return jdata

You may also find a custom field for JSON data input.

like image 98
Rohan Avatar answered Sep 21 '22 12:09

Rohan


You can make forms with fields from JSON data with that decision

Example:

forms.py

# -*- coding: utf-8 -*-
from django import forms
from splitjson.widgets import SplitJSONWidget


class testForm(forms.Form):
    attrs = {'class': 'special', 'size': '40'}
    data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True))

views.py

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import testForm


def test_dict(request):
    json = {'a': 1,
            'b': 2,
            'c': 3,
            'd': 4}
    form = testForm(request.POST or None, initial={'data': json})
    if form.is_valid():
        # validate and save
        pass

    template = 'test_template.html'
    context = RequestContext(request, {'form': form})
    return render_to_response(template, context)

template.py

<!doctype html>
<html>
    <head></head>
    <body>
        Errors: 
        {% for field, error in form.errors.items %}
            <ul>
            <li>{{ error }}</li>
            </ul>
        {% empty %}
            no errors 
        {% endfor %}
        <hr/>
        List of:
            <form action="" method="post">
                {% csrf_token %}
                {{ form.as_p}}
                <input type="submit" value="Submit" />
            </form>
    </body>
</html>

Result:

like image 38
Abbasov Alexander Avatar answered Sep 18 '22 12:09

Abbasov Alexander