AttributeError:myview在Django中的自定义mixin中没有属性对象 [英] AttributeError: myview has no attribute object in custom mixin in Django

查看:395
本文介绍了AttributeError:myview在Django中的自定义mixin中没有属性对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写一个 mixin ,以便能够部分保存表单,并在以后恢复。
当表单很长,用户无法完成一个坐位时,这很有用。以下 mixin 代码直接来自Marty Alchin的 prodjango 书。我在 mixin中的 POST方法的错误代码中发表了评论。下面的详细错误说明。 / p>

从追溯中,我认为错误来自这两个调用 self.get_form(form_class) get_form_kwargs 。但是我不知道如何解决这个问题。



这里是 视图

  class ArticleCreateView(PendFormMixin,CreateView):
form_class = ArticleForm
model = article
template_name =article_create.html
success_url ='/ admin'

strong> mixin

  from django.views。 import.indit导入FormView 
from pend_form.models import PendedForm,PendedValue
from hashlib import md5



class PendFormMixin(object):
form_hash_name ='form_hash'
pend_button_name ='pend'
def get_form_kwargs(self):

返回要传入表单实例化的参数字典
如果恢复一个挂起的表单,这将从数据库中检索数据

form_hash = self.kwargs.get(self.form_hash _name)
printform_hash,form_hash
如果form_hash:
import_path = self.get_import_path(self.get_form_class())
return {'data':self.get_pended_data(import_path ,form_hash)}
else:
print
#print super(PendFormMixin,self).get_form_kwargs()
return super(PendFormMixin,self).get_form_kwargs()

def post(self,request,* args,** kwargs):

用表单数据处理POST请求。如果表单被挂起,它不遵循
正常流程,而是保存值以供以后使用。

if self.pend_button_name in self.request.POST:
printhere
form_class = self.get_form_class()
print form_class
form = self.get_form(form_class)
#这里出现错误,下面打印不执行
#printform is,form
self.form_pended(form)
否则:
super(PendFormMixin,self).post(request,* args,** kwargs)

#自定义方法跟随
def get_import_path(self,form_class):
return'{0}。{1}'。format(form_class .__ module__,form_class .__ name__)
def get_form_hash(self,form):
content =','。在form.fields.keys())中的{1}'。格式(n,form.data [n])
返回md5(内容).hexdigest()
def form_pended(self ,form):
import_path = self.get_import_path(self.get_form_class())
form_hash = self.get_form_hash(f orm)
printin form_pended
pended_form = PendedForm.objects.get_or_create(form_class = import_path,
hash = form_hash)
for form.fields.keys()中的名称:
pended_form.data.get_or_create(name = name,value = form.data [name])
return form_hash
def get_pended_data(self,import_path,form_hash):
data = PendedValue .objects.filter(import_path = import_path,form_hash = form_hash)
返回dict((d.name,d.value)for d在数据中)

错误:

 'ArticleCreateView'没有属性'object'
异常位置:/Users/django/django/lib/python2.7/site-packages/django/views/generic/edit.py in get_form_kwargs,line 125


/Users/pend_form/forms.py在帖子

form = self.get_form(form_class)

/ Users / django / django / lib / py thon2.7 / site-packages / django / views / generic / edit.py in get_form_kwargs

kwargs.update({'instance':self.object})


解决方案

如果您查看django的 CreateView 或其父 BaseCreateView ,您会看到它所做的是分配 self.object = None before调用定义实际形式行为的超类方法。这是因为它是一个 CreateView - 不可能存在编辑对象。



由于您的mixin会覆盖此行为,所以机器的其余部分将在其期望 self.object



添加 self.object =无您的 def post 方法的第一行。


I am trying to write a mixin for able to save a form partially and resume later. This is useful when the form is long and user cannot finish in one-sitting. The mixin code below comes directly from prodjango book by Marty Alchin. I have commented in the code where the error comes which is the POST method in mixin. Detailed error description below.

From the traceback, I think the error comes from these two calls self.get_form(form_class) and get_form_kwargs. but I have no idea how to fix this.

Here is the view:

class ArticleCreateView(PendFormMixin, CreateView):
      form_class = ArticleForm
      model = Article
      template_name = "article_create.html"
      success_url = '/admin'

Here is the mixin:

from django.views.generic.edit import FormView
from pend_form.models import PendedForm, PendedValue
from hashlib import md5



class PendFormMixin(object):
    form_hash_name = 'form_hash'
    pend_button_name = 'pend'
    def get_form_kwargs(self):
        """
        Returns a dictionary of arguments to pass into the form instantiation.
        If resuming a pended form, this will retrieve data from the database.
        """
        form_hash = self.kwargs.get(self.form_hash_name)
        print "form_hash", form_hash
        if form_hash:
            import_path = self.get_import_path(self.get_form_class())
            return {'data': self.get_pended_data(import_path, form_hash)}
        else:
            print "called"
            # print super(PendFormMixin, self).get_form_kwargs()
            return super(PendFormMixin, self).get_form_kwargs()

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests with form data. If the form was pended, it doesn't follow
        the normal flow, but saves the values for later instead.
        """
        if self.pend_button_name in self.request.POST:
            print "here"
            form_class = self.get_form_class()
            print form_class
            form = self.get_form(form_class)
             #the error happens here. below print is not executed
            # print "form is ", form
            self.form_pended(form)
        else:
            super(PendFormMixin, self).post(request, *args, **kwargs)

# Custom methods follow
    def get_import_path(self, form_class):
        return '{0}.{1}'.format(form_class.__module__, form_class.__name__)
    def get_form_hash(self, form):
        content = ','.join('{0}:{1}'.format(n, form.data[n]) for n in form.fields.keys())
        return md5(content).hexdigest()
    def form_pended(self, form):
        import_path = self.get_import_path(self.get_form_class())
        form_hash = self.get_form_hash(form)
        print "in form_pended"
        pended_form = PendedForm.objects.get_or_create(form_class=import_path,
                                                       hash=form_hash)
        for name in form.fields.keys():
            pended_form.data.get_or_create(name=name, value=form.data[name])
        return form_hash
    def get_pended_data(self, import_path, form_hash):
        data = PendedValue.objects.filter(import_path=import_path, form_hash=form_hash)
        return dict((d.name, d.value) for d in data)

Error:

'ArticleCreateView' object has no attribute 'object'
Exception Location:     /Users/django/django/lib/python2.7/site-packages/django/views/generic/edit.py in get_form_kwargs, line 125


/Users/pend_form/forms.py in post

                form = self.get_form(form_class)

/Users/django/django/lib/python2.7/site-packages/django/views/generic/edit.py in get_form_kwargs

            kwargs.update({'instance': self.object})

解决方案

If you look at the definition of django's CreateView, or its parent BaseCreateView, you'll see that all it does is assigns self.object = None before calling super class methods which define the actual form behavior. That's because it's a CreateView - no object to edit could possibly exist.

Since your mixin overrides this behavior, the rest of the machinery fails when it expects self.object to exist as None.

Add self.object = None to the first line of your def post method.

这篇关于AttributeError:myview在Django中的自定义mixin中没有属性对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆