Search code examples
djangomodelclonedjango-class-based-views

Django - Clone model object in Class based ListView


I have a list.html with lots of records and a column containing a button to clone the specific record like this:

{% for betr in object_list %}
    ....
    <td>
        <button type="button" class="btn btn-first" onclick="window.location='../clone/{{betr.ID}}';">
            <span class="fas fa-copy" style="font-size: 1rem;"></span>
        </button>
    </td>
{% endfor %}

My urls.py looks like this:

urlpatterns = [
...
path('update/<int:pk>/', UpdateView.as_view(), name='update'),
path('clone/<int:pk>/', CloneView.cloneRecord(), name='clone'),
...
]

and my views.py contains a clone view with a function to clone the record and open the UpdateView with the cloned record for editing:

class CloneView(LoginRequiredMixin):
    login_url = '/accounts/login/'
    model = mymodel
    def cloneRecord(self,**kwargs):
        record = mymodel.objects.filter(id=self.request.GET['ID'])[0]
        record.id = None
        record.save()
        return http.HttpResponseRedirect(reverse('/update/', kwargs={'pk':record.id}))

At the moment I am receiving following error:

TypeError: cloneRecord() missing 1 required positional argument: 'self'

What am I missing? Any help is appreciated.


Solution

  • if you have seperate urls for both views, then you should write your code in GET method like this

    class CloneView(LoginRequiredMixin, View):
        login_url = '/accounts/login/'
    
        def get(self,**kwargs):
            record = mymodel.objects.filter(id=self.request.GET['ID'])[0]
            record.id = None
            record.save()
            return http.HttpResponseRedirect(reverse('/update/', kwargs={'pk':record.id}))
    

    Your url should be like this

    path('clone/<int:pk>/', CloneView.as_view(), name='clone'),
    

    Remember that as_view is used to call a class based view. You cannot change according to function you are calling.