2

Now heads up! I am fresh noob off the NOOB-BUS from NOOBSVILLE!

So i am workin on a form to load up information and edit that form information and im in a headache. so i am using:

Django: 1.8 Pyhton: 3.5.1 backend is sqlite

I am using a form.ModelForm to load information into but when it comes to saving this is where i am stuck. the documentation is very confusing should i use all or just one clean.

this is the forms.py

    class EditContact(forms.ModelForm):
    class Meta:

    model = Contact
    #the list of all fields

    exclude = ['date_modified']


    def clean(self):
        if self.date_of_entry is None:
            print("looking to see what works")
            self.date_of_entry = datetime.date.today()
            return


    def clean_ContactID(self):
        #see this line below this comment i dunno what it does 
        ContactID= self.cleaned_data.get('ContactID')
        print ("cleaning it")
        # i also dont know what validation code suppose to look like
        # i cant find any working examples of how to clean data
        return ContactID

now there are mainly more def clean_methods but i think what i want to use is clean which should use all but in my view.

this is in view.py

def saveContactInfo (request):

    #this part i get 
    if  request.user.is_authenticated():

        ContactID= request.POST['ContactID']

        a = ListofContacts.objects.get(ContactID=ContactID)


        f = EditContact(request.POST,instance=a)       

        print("plz work!")
        if f.is_valid():
            f.save() 
            return render (request,"Contactmanager/editContact.html",   {'contactID': contactID})
        else:
            return HttpResponse("something isnt savin")

    else:
        return HttpResponse("Hello, you shouldnt ")

and this is model.py

 def clean(self):

    if self.ConactID is None:
        raise  ValidationError(_('ContactID  cant be NULL!'))

    if self.date_of_entry is None:
        print("think it might call here first?")
        self.date_of_entry = datetime.date.today()
        print ( self.date_of_entry  )

    if self.modified_by is not None:
        self.modified_by="darnellefornow"
        print(self.modified_by )

    if self.entered_by  is not None:
        self.entered_by = "darnellefornow"
        print(self.entered_by )
        ContactID = self.cleaned_data.get('ContactID')

    return

now above the model has the fields and the types which all have blank = true and null = true except for the excluded field date_of_entry

and ive gotten to find out that when calling is_valid() in views it calls the models.clean() but it fails to save!!! and i dont know why! i dont know how to do the validation. i would like to know the process and what is required and even an example of form validation a field.

3
  • I really can't understand what you're asking here. If you don't have any custom validation to do on the ContactID field, why are you defining clean_ContactID()? What are you trying to achieve? Commented Aug 16, 2016 at 21:05
  • to be honest, i dont know i was following a tutorial and attempting it with my personal project. so what you are saying is just use clean()? ok i will but it is still failing and i dont know why Commented Aug 17, 2016 at 12:21
  • Ok guys i found the solution to my headache one of my fields for was a dateime and i was entering the date in the wrong format. so it was expecting "08/16/2016" and i was entering "2016/16/08" that was causing it to fail. ( the validation ) so for people in the future! watch the way you entered the data into your forms. ESPCIALLY DATES! Commented Aug 17, 2016 at 16:01

1 Answer 1

2

I think you're wanting info/answers on a couple of things here, looking at your code comments. Hopefully this helps:

1) You only need to use the clean_FIELDNAME functions if you need to handle something custom specifically for that field. The Django docs show this as an example:

def clean_recipients(self):
    data = self.cleaned_data['recipients']
    if "[email protected]" not in data:
        raise forms.ValidationError("You have forgotten about Fred!")

    # Always return the cleaned data, whether you have changed it or
    # not.
    return data

So in that block, they are checking to see if the email list provided contains a particular email.

2) That also shows another question you asked in your comments about how to handle the validation. You'll see in that snippet above, you could raise a forms.ValidationError. This is discussed more here: https://docs.djangoproject.com/en/1.10/ref/forms/validation/

So, if an error is raised in any of those clean_ methods or in the main clean method, the form.is_valid() will be false.

Does that help?

Sign up to request clarification or add additional context in comments.

5 Comments

ok so i should use clean() to clean all got it! also a side question it added the clean method after i did a migrate and it failed to update the migration would that cause any error in cleaning? also i am using modelform so is clean() would work on it as well right? also anyway i can get the system to print out why its failing to edit my contacts? and help with validation would be nice like self.cleaned_data.get['contactID'] im asking for alot i know im just confused
Sure, so migrating only affects the database and updates it based your model changes. I don't think it would have any direct effect on the form clean results unless your model changes are causing validations to fail due to fields be non-nullable or empty. To see why the validation is failing, either try debugging and stepping through the "if condition" that checks f.is_valid(), or printing out to the console with print(f.errors), or displaying in your template the field errors for your user (which you will likely end up doing anyway).
THANK YOU VERY MUCH! you helped me understand the clean() and validation alot better i solved it by removing all clean() and by noticing that i was entering the date for my datetimefield wrong which now is working i can edit data easliy
Great! Glad I could help. If my answer was good enough, please feel free to accept it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.