从 Django 模型中保存数据

Saving data from a modelform Django

现在请注意!我是来自 NOOBSVILLE 的 NOOB-BUS 新手!

所以我正在处理一个表单来加载信息并编辑该表单信息,我很头疼。所以我正在使用:

姜戈:1.8 皮顿:3.5.1 后端是 sqlite

我正在使用 form.ModelForm 将信息加载到其中,但是在保存时这就是我遇到的问题。文档非常混乱,我应该使用全部还是只使用一个干净的。

这是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

现在主要有更多的 def clean_methods 但我认为我想使用的是干净的,应该使用所有但在我看来。

这是在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 ")

这是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

现在模型上方的字段和类型都具有空白 = true 和 null = true,排除字段除外 date_of_entry

我发现当在视图中调用 is_valid() 时它会调用 models.clean() 但无法保存!!!我不知道为什么!我不知道如何进行验证。我想知道流程和要求,甚至是表单验证字段的示例。

我认为您想要 info/answers 了解这里的几件事,查看您的代码注释。希望这会有所帮助:

1) 如果您需要处理专门针对该字段的自定义内容,则只需使用 clean_FIELDNAME 函数。 Django docs show this as an example:

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

所以在那个块中,他们正在检查提供的电子邮件列表是否包含特定电子邮件。

2) 这也显示了您在评论中提出的另一个关于如何处理验证的问题。您会在上面的代码片段中看到,您可以提出 forms.ValidationError。此处对此进行了更多讨论:https://docs.djangoproject.com/en/1.10/ref/forms/validation/

因此,如果在任何这些 clean_ 方法或主要 clean 方法中出现错误,form.is_valid() 将为 false。

有帮助吗?