有没有办法在基于功能的视图中访问模型实例?我在硬编码策略中尝试了下面的代码。我需要它是动态的。
形式:
<form method="POST"
action="{% url 'cadmin:toggle_status' model='Library' %}" #***** Model is hardcoded
class="visible-lg-inline">
{% csrf_token %}
.....
</form>
网址:
path('toggle-status/<slug:model>', toggle_status, name='toggle_status'),
查看:
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'))
答案 0 :(得分:0)
您没有模型实例。如果你想要一个,你需要得到它。
my_instance = MyModel.objects.get(pk=whatever)
答案 1 :(得分:0)
像
这样的东西return HttpResponseRedirect(reverse('cadmin:library_list', kwargs={'model': model}))
和
action="{% url 'cadmin:toggle_status' model={{model}} %}"
答案 2 :(得分:0)
尝试以下
我使用eval来减少代码
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