【问题标题】:How can I pass a model id from the url to a class based view?如何将模型 ID 从 url 传递到基于类的视图?
【发布时间】:2021-02-17 15:39:35
【问题描述】:

我有一个基于类的视图:

class Create(View):
    note_id = None
    http_method_names = ['post', 'patch']

    default_title = "You fool! This was left empty"
    default_body = "Why did you leave this blank :("

    def dispatch(self, *args, **kwargs):
        method = self.request.POST.get('_method', '').lower()
        print('method = ', method)

        if method == 'patch': 
            return self.patch(*args, **kwargs) 

        elif method == 'post': 
            self.post(*args, **kwargs) 

        return super(Create, self).dispatch(*args, **kwargs)
       


    def post(self, note_id): 
        date = datetime.date.today()

        title = self.request.POST.get('title', '')
        body = self.request.POST.get('note', '')

        # check for blank attributes 
        if title == "": 
            title = Create.default_title
            
        if body == "":
            body = Create.default_body
            
        note = Note(note_title=title, note_body=body, publish_date=date, edit_date=None)
        note.save() 


        return HttpResponseRedirect(reverse('notes:note'))




    def patch(self, note_id): 
        note = Note.objects.get(id=note_id)

        title = self.request.POST.get('title', '')
        body = self.request.POST.get('note', '')

        # if something changed
        if title != note.note_title or body != note.note_body: 

            # check for blank attributes 
            if title == "": 
                title = Create.default_title
           
            if body == "":
                body = Create.default_body
                    
            note.note_title = title 
            note.note_body = body
            note.edit_date = datetime.date.today()
            note.save() 

        return HttpResponseRedirect(reverse('notes:note'))

在 url.py 我有

urlpatterns = [
    path('<int:note_id>/create/', views.Create.as_view(), name='create'), 
    path('<int:note_id>/edit/', views.Create.as_view(), name='edit')
]

以前,对于基于函数的视图,note_id 只会自动传递给函数。在基于类的视图中,我无法弄清楚它的等价物。我试过明确地将 note_id 传递给每个函数,但这没有用。我尝试在我的 url.py 中包含 Create.as_view(note_id=note_id),但无济于事。

目前,运行此代码我得到: post() got multiple values for argument 'note_id'

【问题讨论】:

标签: python django


【解决方案1】:

正如上面评论中提到的,您需要通过self.kwargs 访问这些值。例如:

class Create(View):
    note_id = None         # Delete this line
    ...

    # delete the dispatch method - no need to overwrite this.

    # Don't include note_id as an argument, but request should be an argument
    def post(self, request):        
         note_id = self.kwargs['note_id']
         ....

    def put(self, request):        # Likewise here
         note_id = self.kwargs['note_id']
         ....

看起来您不需要编写自定义调度方法。如果您所做的只是调用适当的方法,那么View 免费提供的调度方法就可以了 :)

【讨论】:

  • 你传递给函数的请求来自哪里?自我请求?调度方法会是什么样子?
  • @AviouslyAK 嗨。无需在此处编写自己的调度方法。我已经更新了我的答案,包括一个简短的解释。
猜你喜欢
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
相关资源
最近更新 更多