我认为我遇到了我写过的基于Django类的视图的线程问题。
启动应用程序后,UpdateView可以正常运行,直到调用/访问CreateView。然后,随后的UpdateViews使用在CreateView的get_initial方法中生成的值填充“code”字段。
问题仅在Web服务器上显示,而不是在使用development runserver命令时显示。
E.g。如果MyObject的实例的代码为“123”,则访问UpdateView会将表单中的代码显示为“123”。在访问一个调用CreateView的页面后,get_initial()会生成一个新代码,比如'456'。从那时起,访问任何调用UpdateView的url会在表单中显示“456”而不是实例代码。
示例myproject.app.views.myobject视图类:
from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
from django.views import generic
from myproject.app.forms import MyObjectForm
from myproject.app.models import MyObject
class EditMixin(generic.base.View):
form_class = MyObjectForm
def get_success_url(self):
return self.object.get_absolute_url()
def form_valid(self, form):
self.object = form.save(commit=False)
if not self.object.pk:
self.object.created_by = self.request.user
self.object.updated_by = self.request.user
self.object.save()
messages.success(self.request, 'Object saved.')
return HttpResponseRedirect(self.get_success_url())
class CreateView(EditMixin, generic.edit.CreateView):
model = MyObject
@method_decorator(permission_required('app.add_myobject'))
def dispatch(self, *args, **kwargs):
return super(CreateView, self).dispatch(*args, **kwargs)
def get_initial(self):
initial = super(CreateView, self).get_initial()
#TODO: proper auto-generation of code
myobject = MyObject.objects.order_by('-code')[0]
code = int(myobject.code) + 1
initial.update({'code': str(code)})
return initial
class UpdateView(EditMixin, generic.edit.UpdateView):
@method_decorator(permission_required('app.change_myobject'))
def dispatch(self, *args, **kwargs):
return super(UpdateView, self).dispatch(*args, **kwargs)
def get_queryset(self):
return MyObject.objects.filter(created_by=self.request.user)
网址格式:
from myproject.app.views import myobjects
urlpatterns = patterns('',
url(r'^$', myobjects.ListView.as_view(), name='myobject_list'),
url(r'^(?P<pk>[\d]+)/$', myobjects.DetailView.as_view(),
name='myobject_detail'),
url(r'^(?P<pk>[\d]+)/edit$', myobjects.UpdateView.as_view(),
name='myobject_edit'),
url(r'^new$', myobjects.CreateView.as_view(),
name='myobject_new'),
)
任何人都可以帮助解释我可能导致线程问题的位置,以及避免这种情况的最佳做法吗?
答案 0 :(得分:1)
尝试删除对super的get_initial的调用。它似乎使用类属性而不是实例属性,导致您遇到麻烦。试试这个:
def get_initial(self):
myobject = MyObject.objects.order_by('-code')[0]
code = int(myobject.code) + 1
initial={'code': str(code)}
return initial