如何在django admin中选择单选按钮时隐藏/显示字段? [英] How hide/show a field upon selection of a radio button in django admin?

查看:288
本文介绍了如何在django admin中选择单选按钮时隐藏/显示字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

models.py

models.py

from django.db import models
from django.contrib.auth.models import User

STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),)
class Leave(models.Model):
    ----
    ----
    ----
    ----
    status = models.IntegerField(choices=STATUS_CHOICES, default = 0)
    reason_reject = models.CharField(('reason for rejection'),max_length=50, blank=True)

    def __str__(self):
        return self.name

admin.py

from django.contrib import admin
from .models import Leave

@admin.register(Leave)
class LeaveAdmin(admin.ModelAdmin):
    ------
    ------
    -----

    class Media:
        js = ('/static/admin/js/admin.js')

-
admin.js

- admin.js

    (function($) {
    $(function() {
        var reject = document.getElementById('id_status_0')
        var accept = document.getElementById("id_status_1")
        var reason_reject = document.getElementById("id_reason_reject")
        if (accept.checked == true){
            reason_reject.style.display = "none"
        }
        else{
            reason_reject.style.display = "block"
        }
    });
})(django.jQuery);

现在我已经在admin.py中导入了文件,如何触发jQuery函数,以便它有效。

Now I have imported the file in the admin.py, How do I trigger the jQuery function such that it works.

更新 -

该功能有效,但我需要重新加载页面使该字段出现和消失。我想要一些与HTML中的'点击'事件相同的东西。我不知道Javascript。

the function works but, I need to reload the page to make the field appear and disappear. I want some thing equivalent to 'on-click' event in HTML. I have no idea about Javascript.

推荐答案

$(function() {
    $('input[name="status"]').on('click', function() {
        if ($(this).val() == '0') {
            $('#id_reason_reject').show();
        }
        else {
            $('#id_reason_reject').hide();
        }
    });
})

这篇关于如何在django admin中选择单选按钮时隐藏/显示字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆