-2

Is there a way to access model instance in function based view? I tried the code below in a hardcoded strategy. I need it to be dynamic.

Form:

<form method="POST" 
      action="{% url 'cadmin:toggle_status' model='Library' %}" #***** Model is hardcoded
      class="visible-lg-inline">
{% csrf_token %}
.....
</form>    

URL:

path('toggle-status/<slug:model>', toggle_status, name='toggle_status'),

View:

def toggle_status(request, model):
    /******* How can i access model instance here? *********/
    if request.POST:    
        toggle_status = request.POST.get('toggle-status')
    pk = request.POST.get('pk')
    if toggle_status and pk:
        if model == "Zone":
            Zone.objects.filter(pk=pk).update(status=toggle_status)
        if model == "Library":
            Library.objects.filter(pk=pk).update(status=toggle_status)
    return HttpResponseRedirect(reverse('cadmin:library_list'))
ohid
  • 155
  • 1
  • 13

3 Answers3

0

You don't have a model instance. If you want one, you need to get it.

my_instance = MyModel.objects.get(pk=whatever)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Something like

return HttpResponseRedirect(reverse('cadmin:library_list', kwargs={'model': model}))

and

action="{% url 'cadmin:toggle_status' model={{model}} %}"

?

art
  • 1,358
  • 1
  • 10
  • 24
0

Try the following
I use eval for less code

def toggle_status(request, model):
    if request.POST:    
        toggle_status = request.POST.get('toggle-status')
        pk = request.POST.get('pk')
        if toggle_status and pk:
           if model == "Zone" or model == 'Library':
               # it's like I  was doing : Zone.Objects.get(pk=pk) or Library.object.get(pk=pk)
               instance = eval("%s.objects.get(pk=pk)" % model) # Not filter
               instance.status = toggle_status 
               instance.save()
           return HttpResponseRedirect(reverse('cadmin:library_list'))
  # rest of the code
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50