简体   繁体   English

保存来自Django的数据

[英]Saving data from a modelform Django

Now heads up! 现在抬头! I am fresh noob off the NOOB-BUS from NOOBSVILLE! 我是NOOBSVILLE的NOOB-BUS上的新菜鸟!

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 Django:1.8 Pyhton:3.5.1后端是sqlite

I am using a form.ModelForm to load information into but when it comes to saving this is where i am stuck. 我正在使用form.ModelForm将信息加载到其中,但是在保存时,这就是我遇到的问题。 the documentation is very confusing should i use all or just one clean. 该文档非常令人困惑,如果我使用全部或仅一种清洁方式。

this is the forms.py 这是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. 现在主要有更多的def clean_methods,但是我认为我要使用的是clean,应该使用所有,但在我看来。

this is in view.py 这是在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 这是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 现在,模型上方的字段和类型都具有空白= true和null = true,但排除的字段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!!! 我已经发现在视图中调用is_valid()时会调用models.clean(),但是无法保存! 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. 我想知道流程和所需的内容,甚至是表单验证字段的示例。

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. 1)仅在需要处理专门针对该字段的自定义内容时,才需要使用clean_FIELDNAME函数。 The Django docs show this as an example : Django文档将其作为示例

def clean_recipients(self):
    data = self.cleaned_data['recipients']
    if "fred@example.com" 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. 2)这也显示了您在评论中询问的另一个问题,即如何处理验证。 You'll see in that snippet above, you could raise a forms.ValidationError. 您会在上面的代码段中看到,可以引发一个forms.ValidationError。 This is discussed more here: https://docs.djangoproject.com/en/1.10/ref/forms/validation/ 在此处进行更多讨论: 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. 因此,如果在任何clean_方法或主clean方法中引发错误,则form.is_valid()将为false。

Does that help? 有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM