Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在与基于类的FormView一起使用的模板中显示当前对象_Python_Django_Formview - Fatal编程技术网

Python 如何在与基于类的FormView一起使用的模板中显示当前对象

Python 如何在与基于类的FormView一起使用的模板中显示当前对象,python,django,formview,Python,Django,Formview,具有以下URL.py代码段: url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required( StorageItemTransactionAddView.as_view()), name='storage_item_transaction'), 但此时无法访问该方法。所以我想知道怎样才能用正确的方法来做?我所需要的只是 self.object = StorageItem.objects.get

具有以下URL.py代码段:

url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required(
    StorageItemTransactionAddView.as_view()), 
    name='storage_item_transaction'),
但此时无法访问该方法。所以我想知道怎样才能用正确的方法来做?我所需要的只是

self.object = StorageItem.objects.get(pk='my pk')
您可以覆盖以传递额外的上下文:

...

def get_context_data(self, **kwargs):
    context = super(ItemCreate, self).get_context_data(**kwargs)
    context['storage_item'] = StorageItem.objects.get(pk=self.kwargs['pk'])
    return context

为什么不简单地执行以下操作:

class StorageItemTransactionAddView(View):

    def post(self, request, pk):
        storage_item = StorageItem.objects.get(pk=pk)
        ...
        return render(request, 'myapp/index.html', {'object': storage_item})
<h1>{{ object.name }}</h1>
现在,在模板中,可以执行以下操作:

class StorageItemTransactionAddView(View):

    def post(self, request, pk):
        storage_item = StorageItem.objects.get(pk=pk)
        ...
        return render(request, 'myapp/index.html', {'object': storage_item})
<h1>{{ object.name }}</h1>
{{object.name}
希望能有帮助