Django


1350 浏览 6 years, 1 month

6.11 常见问题

版权声明: 转载请注明出处 http://www.codingsoho.com/

Issue

form.save(commit=False)保存时会创建一个新的实例

解决方式:要指定instance

form = self.form_class(request.POST, instance=self.get_object())  
        if form.is_valid():            
            user = form.save(commit=False)

或者调用

form = self.get_form() 
    def get_form(self, form_class=None):
        """
        Returns an instance of the form to be used in this view.
        """
        if form_class is None:
            form_class = self.get_form_class()
        return form_class(**self.get_form_kwargs()) 
    def get_form_kwargs(self):
        """
        Returns the keyword arguments for instantiating the form.
        """
        kwargs = super(ModelFormMixin, self).get_form_kwargs()
        if hasattr(self, 'object'):
            kwargs.update({'instance': self.object})
        return kwargs   
    def get_form_kwargs(self):
        """
        Returns the keyword arguments for instantiating the form.
        """
        kwargs = {
            'initial': self.get_initial(),
            'prefix': self.get_prefix(),
        }

        if self.request.method in ('POST', 'PUT'):
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        return kwargs   
RegistrationForm' object has no attribute 'clean_data

关于Django中出现上述问题的解决方法
code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Newfo...Karen
上述网址第八条
Django语法更新 Newforms:clean_data------>cleaned_data