以Django形式将值从一个字段传递到另一字段

时间:2018-12-04 09:37:45

标签: django django-models django-forms django-views

我有两个Django模型ModelA和ModelB。

class ModelA(models.Model):
    fieldA1 = models.CharField()
    fieldA2 = models.CharField()
    fieldA3 = models.ManyToManyField('ModelC')

class ModelB(models.Model):
    key = models.CharField()
    value = models.CharField()

和django形式:

class MyForm(forms.ModelForm):
    A_fields =[field.name for field in ModelA._meta.get_fields()]
    key= forms.ChoiceField(label='Key',choices = [(str(l),str(l)) for l in A_fields])
    value= forms.MultipleChoiceField(label='Value',choices = 'Need Help here'). 

    'I have used MultipleChoiceField because if key == fieldA3 then there could be multiple choices for this field.'

    class Meta:
        model = ModelB
        fields = ('key', 'value')

因为“键”字段的选择是ModelA的字段名称。我希望基于所选的键(将是ModelA的某些字段名称),对于MyForm中“值”字段显示的选择必须是存储在ModelA的该特定字段中的所有值。

我知道如何获取存储在ModelA特定字段中的值。我必须使用以下命令。

field_values = ModelA.objects.values('Field for which i want values')

这是视图:

def MyPageView(request):
    if request.method == 'POST':
        form1 = MyForm(request.POST)
        if form1.is_valid():
            myform = form1.save(commit=False)
            return HttpResponseRedirect('/new_page')
    else:
        return render(request,'app1/my_page.html',{'form1':form1})

这是my_page.html

  <form method= "post">
    {% csrf_token %}
    {{ form1.as_p }}
    <input type="submit" name="Save">
 </form>

我该如何解决这个问题?提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为您需要发送AJAX请求以获取字段value的选择。

后端

url(r'^value_choices/$', views.ValueChoicesView.as_view(), name='value-choices')

import json
from django.http import HttpResponse
from django.views import View

class ValueChoicesView(View):
    def get(self, request, *args, **kwargs):
        key = request.GET.get('key')
        if key is None:
            return HttpResponse(json.dumps({
                "error": "Field 'key' is required."
            }), content_type='application/json')
        # another validation would be if the key belongs in `ModelA`

        data = []
        key_qs = ModelA.objects.all().values(key)

        for item in key_qs:
            if item[key] not in data:
                data.append(item[key])

        return HttpResponse(json.dumps({"data": data}), content_type="application/json")

前端

// assuming you are using jQuery
$(document).on('change', '#idOfKeyDropdown', function() {
    var chosenKey = $(this).children("option:selected").val();
    var data = {"key": chosenKey};

    $.ajax({
        url: "value_choices",
        type: "GET",
        data: data,
        dataType: "json",
        success: function(response) {
            if (response.data) {
                var valueDropdown = $('#idOfValueDropdown');

                // empty value dropdown and add options
                valueDropdown.empty();

                for (var item of response.data) {
                    valueDropdown.append('<option value=' + item + '>' + item + '</option>');
                }                    
            }
        },
        error: function(err) {
            // handle error here
        }
    });
});

参考
 * AJAX Docs
 * How to make an AJAX request without jQuery