Amandeep Singh
Amandeep Singh

Reputation: 1431

Passing value from one field to other field in django form

I have two django models ModelA and 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()

and a django form:

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')

Since choices for 'key' field are the field names of ModelA. I want that based on the key selected (which will be some field name of ModelA), choices shown for the 'value' field in MyForm must be all the values stored in that particular field of ModelA.

I know how to fetch values stored in a particular field of ModelA.I have to use the following command.

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

This is the view:

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})

Here is my_page.html

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

How do i approach this problem? Thanks in advance.

Upvotes: 0

Views: 1797

Answers (1)

Sachin
Sachin

Reputation: 3664

I think you will need to send an AJAX request to get the choices for field value.

Backend:

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")

Frontend:

// 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
        }
    });
});

Ref:
* AJAX Docs
* How to make an AJAX request without jQuery

Upvotes: 1

Related Questions