Tuesday, June 4, 2013

ASSIGNING VALUES TO DJANGO FORM BEFORE SAVING (Assigning default values to django form)


Sometime you need to exclude certain fields becuase they are not of much importance while taking input form the user. In that case If you have not included the fields in the form and wish to fill it with some data before saving then you are reading the appropriate post.

in the views file write a simple function as you could have written for the other forms. The difference is that instead of calling the form.save(commit = True) method you need to call form.save(commit = False), then do the processing on the posted data and then save it by calling the save() method. The sample code is given below to elaborate further.

The image given below contains only three fields out of six in the model. I will take input form the user in the three fields bit save data in all the six columns. Lets have a look how that is done.




Keep in mind that if you have made the forms from models then this will automatically be saved in the fields that you have made visible on the form. I have written this sample just to elaborate that different processing can be done when the data is posted. I have tried to explain by simply saving the posted data in excluded form fields. The fields description and type are not visible on the form, but when the form is submitted these fields will also be filled with the data.

def add_record(request,template):
    if request.method == "POST":
        # Its the name of the form in the forms.py file
        form = RecordForm(request.POST)
        if form.is_valid():
            # Instead we called this method to tell dont save data because we
# have to perform a job
            temp = form.save(commit=False)
            # the type is a column in model so i am saving "v" in that column
            temp.type = 'v'
            # description is another field in the model, so i am saving posted 
xml in that field as well for backup            
            temp.description = request.POST["xml_dump"]
            #Now saving the form          
            temp.save()
            response = {'status':True,}
        else:
         
            t = Template("<ul>{% for field in form %}\
                            <li>{{field.label_tag}} : {{ field.errors|striptags }}</li>\
                            {% endfor %}</ul>")
            c = Context({"form": form})
            response = {'status':False,'errors':t.render(c)}
     
        message = "Record added successfully"
        return render_to_response('done.html',{'message':message}, context_instance=RequestContext(request))
    else:
        form = RecordForm()
    return render_to_response(template,{'form':form}, context_instance=RequestContext(request))