通过弹出视图添加值时自动填充select2

时间:2018-12-21 13:30:15

标签: javascript django javascript-events django-admin jquery-select2

我有一个Web应用程序,用于管理具有以下指定的组和标签的事件:

#model.py

class Event(models.Model):
    name = models.CharField('Event Name', max_length=100, help_text='Insert a name for the event')
    tags = models.ManyToManyField('Tag')
    group = models.ForeignKey('Group', on_delete=models.SET_NULL, null=True)

class Group(models.Model):
    name = models.CharField('Group name', max_length=50, help_text='Insert a name for the group')
    description = models.CharField('Description', max_length=100, help_text='Insert a description for the group (optional)', blank=True)

    class Meta:
        verbose_name_plural = "Groups"
        ordering = ['name']

    def __str__(self):
        return self.name

class Tag(models.Model):
    name = models.CharField('Tag name', max_length=50, help_text='Insert a name for the Tag')
    group = models.ForeignKey('Group', on_delete=models.SET_NULL, null=True)

    class Meta:
        ordering = ['name']
        # to avoid accepting a tag with the same value & group
        unique_together = ['name', 'group']

    def __str__(self):
        return self.name

我希望选择与 group 值链接的 tags 字段。 为此,我从这些讨论中获得了启发: -https://stackoverflow.com/a/48608535 -https://stackoverflow.com/a/47843768

所以我覆盖了我的 change_form.html

{% extends 'admin/change_form.html' %}

{% block admin_change_form_document_ready %}
    {{ block.super }}
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
    <script type="text/javascript">
    var url = 'myUrl';

    getRelatedTags(url);

    /* get tags related to a group */
    function getRelatedTags(url)
    {
        // initiate select2
        $("#id_tags").select2({});


        // make initial call to populate tags related to group
        $.getJSON(url, {id: $('select#id_group').val()}, function(j){ 
                var options = '';
                for (var i = 0; i < j.length; i++) { 
                    options += '<option value="' + j[i].id + '">' + j[i].name + '</option>'; 
                } 
                // inspect html to check id of subcategory select dropdown.
                $("select#id_tags").html(options); 
             }); 


        //$(document).on('change', "select#id_group", function()
        // bind load + change simultaneously
        $('select#id_group').bind('change', function () 
        {   
            $("#id_tags").select2("val", "");
            if($(this).val())
            {
                group_id = $(this).val();
            }
            else
                group_id = 0;

            $.getJSON(url, {id: group_id}, function(j){ 
                var options = '';
                for (var i = 0; i < j.length; i++) { 
                    options += '<option value="' + j[i].id + '">' + j[i].name + '</option>'; 
                } 
                // inspect html to check id of subcategory select dropdown.
                $("select#id_tags").html(options); 
             }); 
        });
        $('select#id_group').trigger('change');
    }

    </script>
{% endblock %}

这是视图的代码:

def get_related_tags_to_group(request):
    if request.is_ajax():
        group_id = request.GET.get('id','') 
        result = list(Tag.objects.filter(group__id=int(group_id)).values('id', 'name')) 
    else:
        result = {}

    return HttpResponse(json.dumps(result), content_type="application/json") 

当我通过单击+图标(在管理员视图中)添加新标签时,会出现问题:输入新的“标签”值后,select2不会更新,但会插入到select2结果列表中> ul.select2-id_tags-结果

0 个答案:

没有答案