Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change form field values after calling the is_valid() method?

How can I change form field values after calling the is_valid() method?

I am trying to alter the field u_id after I validate the data with form.is_valid (this is required). I can alter the data, even display it in the HttpResponse, but I cannot write it into my Postgresql DB. Any ideas?

class ProductForm(forms.ModelForm):
    class Meta:
            model = Product

class Product(models.Model):
    p_name = models.CharField(max_length=30)
    u_id = models.CharField(max_length=80)

def uploadImage(request):
    if request.method == 'POST':
        form1 = ProductForm(request.POST, prefix="product")
        if form.is_valid() and form1.is_valid():
            form1.cleaned_data['uid']='12134324231'
            form1.save()

            return HttpResponse(form1.cleaned_data['p_name'])

    return render_to_response('upload.html', {'form': form, 'form1': form1},            RequestContext(request))
like image 439
LonnyT Avatar asked Nov 24 '13 17:11

LonnyT


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.

What is clean data in Django?

cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).

How do you validate a form in Python?

You can use is_valid() when required to validate complete form-data. This validation will check for Python-datatypes. This function will return True or False (Python Data Types) in return.


2 Answers

Save the model form with commit=False, then modify the instance before saving to the database.

if form.is_valid() and form1.is_valid():
    instance = form1.save(commit=False)
    instance.uid = '12134324231'
    instance.save()

If form1 had any many-to-many relationships, you would have to call the save_m2m method to save the many-to-many form data. See the docs for full details.

like image 176
Alasdair Avatar answered Oct 17 '22 16:10

Alasdair


From Overriding clean() on a ModelFormSet.

Also note that by the time you reach this step, individual model instances have already been created for each Form. Modifying a value in form.cleaned_data is not sufficient to affect the saved value. If you wish to modify a value in ModelFormSet.clean() you must modify form.instance:

from django.forms import BaseModelFormSet

class MyModelFormSet(BaseModelFormSet):
    def clean(self):
        super(MyModelFormSet, self).clean()

        for form in self.forms:
            name = form.cleaned_data['name'].upper()
            form.cleaned_data['name'] = name
            # update the instance value.
            form.instance.name = name

So what you should do is:

if form.is_valid() and form1.is_valid():
        form1.instance.uid ='12134324231'
        form1.save()
like image 33
Cloud Avatar answered Oct 17 '22 16:10

Cloud