如何在Django中为用户端预填充FilteredSelectMultiple的选定框?

时间:2018-07-24 01:28:47

标签: javascript python jquery html django

我试图在用户重新访问该页面时将其选择的项目显示在FilteredSelectMultiple选择框中。我尝试通过javascript附加选项,但没有帮助。我已经看到了关于如何也预填充相同小部件的stackoverflow问题,但这似乎仅适用于管理员方面。我的FilteredSelectMultiple小部件位于用户端。

这是我使用的代码:

models.py:

class Roles(models.Model):
    role_id = models.AutoField(primary_key=True)
    role_name = models.CharField(max_length=18,
                                 unique=True,
                                 validators=[letters_only])

class Staffs(models.Model):
    staff_id = models.AutoField(primary_key=True)
    admission_number = models.CharField(max_length=5,
                                        unique=True,
                                        help_text="Enter 5 digits",
                                        validators=[numeric_only, MinLengthValidator(5)])
    staff_full_name = models.CharField(max_length=70,
                                       help_text="Enter staff's full name",
                                       validators=[letters_only])
    created_by = UserForeignKey(auto_user_add=True,
                                editable=False,
                                related_name="staff_created_by",
                                db_column="created_by")
    created_at = models.DateTimeField(auto_now_add=True,
                                      editable=False)
    updated_by = UserForeignKey(auto_user=True,
                                editable=False,
                                related_name="staff_updated_by",
                                db_column="updated_by")
    updated_at = models.DateTimeField(auto_now=True,
                                      editable=False)
    roles = models.ManyToManyField(Roles, through='Designations')

class Designations(models.Model):
    designation_id = models.AutoField(primary_key=True)
    curriculum = models.ForeignKey(Curricula, on_delete=models.CASCADE)
    role = models.ForeignKey(Roles, on_delete=models.CASCADE)
    staff = models.ForeignKey(Staffs, on_delete=models.CASCADE)

forms.py:

class ModuleCoordinatorForm(forms.ModelForm):
    class Media:
        css = {
            'all': ('admin/css/responsive.css', 'admin/css/base.css', 'admin/css/widgets.css',)
        }
        js = ('/admin/jsi18n',)

    class Meta:
        model = Designations
        fields = ['module_coordinator', 'role_mc']

    module_coordinator = forms.ModelMultipleChoiceField(queryset=Staffs.objects.all(),
                                                        widget=FilteredSelectMultiple("Module Coordinator",
                                                                                      is_stacked=False),
                                                        required=False,
                                                        label="")

    role_mc = forms.ModelChoiceField(queryset=Roles.objects.all(), widget=forms.HiddenInput,
                                     initial=Roles.objects.get(role_name='Module Coordinator'))

views.py:

def module_coordinator(request):
    c = request.GET.get('curriculum')
    c = int(c)
    mc = request.GET.get('mc')
    staffs = request.GET.get('staffs')
    staffs = staffs.replace('[', '')
    staffs = staffs.replace(']', '')
    staffs = staffs.split(",")
    staffs = [i.replace('"', '') for i in staffs]
    staffs = [ast.literal_eval(i) for i in staffs]

    # code for saving into db
    if request.is_ajax:
        for staff in staffs:
            if Designations.objects.filter(curriculum_id=c, role_id=mc, staff_id=staff).exists():
                pass
            else:
                Designations(curriculum_id=c, role_id=mc, staff_id=staff).save()

    data = {
        'result': 'Module Coordinators Assigned Successfully'
    }
    return JsonResponse(data)


class DesignationsView(TemplateView):
    template_name = 'curricula/designations.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['mc_form'] = ModuleCoordinatorForm(self.request.GET or None)

        context['curriculum'] = Curricula.objects.get(
            course_period__course__course_abbreviation=self.kwargs.get('course_abbr'),
            module_period__module__module_abbreviation=self.kwargs.get('module_abbr'),
            course_period__period__academic_year=self.kwargs.get('year'),
            course_period__period__semester=self.kwargs.get('semester'),
            stage=self.kwargs.get('stage')).pk

        mc_qs = Designations.objects.filter(role__role_name='Module Coordinator',
                                            curriculum__course_period__course__course_abbreviation=self.kwargs.get(
                                                'course_abbr'),
                                            curriculum__module_period__module__module_abbreviation=self.kwargs.get(
                                                'module_abbr'),
                                            curriculum__course_period__period__academic_year=self.kwargs.get('year'),
                                            curriculum__course_period__period__semester=self.kwargs.get('semester'),
                                            curriculum__stage=self.kwargs.get('stage')
                                            ).values_list('staff', flat=True)

        chosen_mcs_name = []
        chosen_mcs_id = []
        for mc in mc_qs:
            chosen_mc = Staffs.objects.get(pk=mc)
            chosen_mcs_name.append(chosen_mc)
            chosen_mcs_id.append(mc)
        # print(chosen_mcs_name)
        print(chosen_mcs_id)

        # chosen_mcs_name_json = json.dumps(chosen_mcs_name)
        # print(chosen_mcs_name_json)

        context['chosen_mc_name'] = chosen_mcs_name
        context['chosen_mc_value'] = chosen_mcs_id

        return context

urls.py:

 path('courses/<str:course_abbr>/<str:module_abbr>/<int:year>/<int:semester>/<int:stage>/designations',
         views.DesignationsView.as_view(), name='designations'),
    path('ajax/module_coordinator/', views.module_coordinator, name="module_coordinator")

designations.html:

{% extends "main_template.html" %}
{% load static %}
{% block title %}Designations{% endblock %}
{% block css %}
    <style>
        hr {
            display: block;
            margin: 0.5em auto;
            border: 1px inset;
        }
    </style>
{% endblock %}
{% block content %}
    {% include 'navbar_architect.html' %}
    {{ mc_form.media }}
    <div id="content" class="colM">
        <div id="content-main">
            <h2>Assign Module Coordinator(s)</h2>
                <form enctype="multipart/form-data" method="post" novalidate>
                    {% csrf_token %}
                    {{ mc_form.non_field_errors }}
                    <input type="hidden" value="{{ curriculum }}" id="id_curriculum_mc">
                    {{ mc_form.role_mc }}
                    <div>
                        <fieldset class="module aligned">
                            <div class="form-row">
                                <div>
                                    <div class="fieldWrapper related-widget-wrapper">
                                        <div class="selector">
                                            {{ mc_form.module_coordinator.errors }}
                                            {{ mc_form.module_coordinator }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-primary float-right" id="mc_btn">Assign</button>
                        </fieldset>
                    </div>
                </form>
            <hr>
        </div>
    </div>
{% endblock %}
{% block javascript %}
    <script>
        $(document).ready(() => {
            let value = "{{ chosen_mc_value }}";
            value = value.replace('[', '');
            value = value.replace(']', '');
            value = value.split(",").map(Number);
            console.log(value);
            let name = "{{ chosen_mc_name }}".replace(/&lt;Staffs: /g, '');
            name = name.replace(/&gt;/g, '');
            name = name.replace('[', '');
            name = name.replace(']', '');
            name = name.split(", ");
            console.log(name);

            for (let i = 0; i < value.length; i++) {
                $("#id_module_coordinator_to").append(`<option value="${value[i]}">${name[i]}</option>`); //doesn't work
            }

            $('#mc_btn').click(function () {
                $('#id_module_coordinator_to option').prop('selected', true);
                let curriculum = $("#id_curriculum_mc").val();
                let mc = $("#id_role_mc").val();
                let staffs = $("#id_module_coordinator_to").val();

                if ($("#id_module_coordinator_to").has('option').length === 0) {
                    return false;
                }

                $.ajax({
                    url: '{% url 'module_coordinator' %}',
                    data: {
                        'curriculum': curriculum,
                        'mc': mc,
                        'staffs': JSON.stringify(staffs)
                    },
                    dataType: 'json',
                    success: function (data) {
                        swal({
                            title: data.result,
                            toast: true,
                            position: 'top-end',
                            type: 'success',
                            showConfirmButton: false,
                            allowEscapeKey: false,
                            allowOutsideClick: false,
                            backdrop: false,
                            timer: 1500,
                        })
                    },
                    error: function () {
                        swal({
                            title: "Unable to assign",
                            toast: true,
                            position: 'top-end',
                            type: 'error',
                            showConfirmButton: false,
                            allowEscapeKey: false,
                            allowOutsideClick: false,
                            backdrop: false,
                            timer: 1500,
                        })
                    }
                });
            });
        });
    </script>
{% endblock %}

注意:swal是一个Javascript警报通知库

1 个答案:

答案 0 :(得分:0)

尝试使用表单

class ModuleCoordinatorForm(forms.ModelForm):
   def __init__(self, *args, **kwargs):
     super(ModuleCoordinatorForm, self).__init__(*args, **kwargs)
     if self.instance.pk:
          self.fields['module_coordinator'].initial = self.instance.staff.all()
          self.fields['role_mc'].initial = self.instance.role.all()

或视图中的

def edit_designations(request, id_designation):
   if request.method == 'GET':
     designation = get_object_or_404(Designations, pk=id_designation)
     form = ModuleCoordinatorForm(instance=designation)      
     form.fields['module_coordinator'].initial = form.instance.staff.all()
     form.fields['role_mc'].initial = form.instance.role.all()
   return render(request, 'designation.html', {'form': form})