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

25πŸ‘

βœ…

It should be:

def get_object(self, queryset=None):
    obj = Portfolios.objects.get(id=self.kwargs['id'])
    return obj

Look at class based generic view dispatch explains that keyword arguments are assigned to self.kwargs.:

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    self.request = request
    self.args = args
    self.kwargs = kwargs
    return handler(request, *args, **kwargs)
πŸ‘€bmihelac

7πŸ‘

id = self.request.GET.get('id',None) is what you needed when trying to access the GET query string.

However, your view can be simplified:

from django.conf.urls import *
from django.views.generic import UpdateView
from yourapp.models import Portfolios
from yourapp.forms import PortfoliosCreateForm

urlpatterns = patterns('',
    url('^portfolios/update/(?P<pk>[\w-]+)$', UpdateView.as_view(
        model=Portfolios,
        form_class=PortfoliosCreateForm,
        template_name='portfolios/create.html',
        success_url='/portfolios'
    ), name='portfolio_update'),
)
πŸ‘€Burhan Khalid

0πŸ‘

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/<pk>/', MyUpdateView.as_view(),name='xyz')

my_model_view.html

{{form}}

You will be able to edit ModelName at url /xyz/<pk>/ where <pk> 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.

πŸ‘€Aseem

Leave a comment