How do I use an UpdateView to update a Django Model?

前端 未结 3 1550
自闭症患者
自闭症患者 2020-12-13 20:06

I\'m trying to update a model in Django using the class-based generic view UpdateView.

I read the page Updating User model in Django with class based UpdateView to t

3条回答
  •  孤城傲影
    2020-12-13 20:36

    views.py

    class MyUpdateView(UpdateView):
        model = ModelName  # required
        template_name = 'x/h1.html'
        form_class = ModelNameForm
        success_url = reverse_lazy('app:page1')
    
        def get_queryset(self):
            """
            Optional condition to restrict what users can see
            """
            queryset = super().get_queryset()
            return queryset.filter(id__lt=20)
    
        def get_success_url(self):
            return reverse_lazy(
                'app1:abc',
                kwargs={'pk': self.object.id}
            )
    

    urls.py

    In urlpatterns=[]

    path('xyz//', MyUpdateView.as_view(),name='xyz')
    

    my_model_view.html

    {{form}}
    

    You will be able to edit ModelName at url /xyz// where can be anything from 1 to 20 based on our condition in get_queryset(). Take that condition out to allow users to edit any object.

    self.object is only available after post request to the UpdateView.

提交回复
热议问题