Thursday, March 21, 2013

ASSIGNING A QUERY RESULT TO DJANGO FORMS AND ASSIGNING A CLASS TO A DJANGO FORM FIELD

In Django if you chose to make forms from the models. Its really easier in a sense that you don't need to describe a separate HTML defining each and every field. By calling some Django forms functions things can be easily validated so you no longer need POST's to fetch data from html field. Just post the form and the Django will take care of all the other stuff.

In this post i am going to describe how to assign jquery classes and filtered queries to forms field in order to assign them some filtered data before they are shown on screen.
So you need to navigate into the forms.py file and write a little code


class FormName(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(FormName, self).__init__(*args, **kwargs)


Now Assign the queryset or the jquery classes in init function
If  you want to assign a query set then write django query like the one given
self.fields['author'].queryset = Author.objects.filter(Books__title__icontains = "Beautiful")
If you want to assign a JQuery class then follow the code written below
self.fields['author'].widget.attrs['class'] = 'required'
The "required" class is the class that is written to validate that the field on which it is applied must not remain empty.


        ajax = true
        data = {}
        $('.required').each(function(){
            $(this).css('border', '1px solid eee');
            data[$(this).attr('author')] = $(this).val()
            if ($.trim($(this).val()) == "") {
                $(this).css('border', '2px solid red');
                ajax = false
            }
            else
            {
                $(this).css('border', '1px solid #A9A9A9');
            }
        })

This is the required class that is placed in my .js file. So using this way you can asssign a dataset and jquery classes to django forms field.

No comments:

Post a Comment