Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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
Django 如何在基于类的视图中调用和使用URL中给出的pk?_Django_Django Models_Django Forms_Django Views_Django Templates - Fatal编程技术网

Django 如何在基于类的视图中调用和使用URL中给出的pk?

Django 如何在基于类的视图中调用和使用URL中给出的pk?,django,django-models,django-forms,django-views,django-templates,Django,Django Models,Django Forms,Django Views,Django Templates,我在URL中有这个代码 from .views import testview urlpatterns = [ path('test/<pk>', testview.as_view(), name='test') ] 那么,我如何在url中获取pk,并在视图中使用它呢?您可以在视图的调度过程中获取对象,并且url参数被添加到视图的kwargs class TestFormView(FormView): template_name = 'test/test.html

我在URL中有这个代码

from .views import testview

urlpatterns = [
    path('test/<pk>', testview.as_view(), name='test')
]

那么,我如何在url中获取
pk
,并在视图中使用它呢?

您可以在视图的
调度过程中获取对象,并且url参数被添加到视图的
kwargs

class TestFormView(FormView):
    template_name = 'test/test.html'
    form_class = ExampleForm
    book = None

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

        self.book = get_object_or_404(
            Book, pk=kwargs.get('pk')
        )
        return super().dispatch(request, *args, **kwargs)

阅读这些文件可能有用

您可以使用
self.kwargs
访问URL参数

例如:

class testview(FormView):
    template_name = 'test/test.html'
    form_class = ExampleForm

    def form_valid(self, form):
        pk_from_url = self.kwargs['pk']
        # rest of your code
类测试视图(FormView):
模板名称='test/test.html'
form\u class=示例form
def表单_有效(自身、表单):
pk_from_url=self.kwargs['pk']
#代码的其余部分
class testview(FormView):
    template_name = 'test/test.html'
    form_class = ExampleForm

    def form_valid(self, form):
        pk_from_url = self.kwargs['pk']
        # rest of your code