0

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.

Amandeep Singh
  • 1,371
  • 1
  • 11
  • 33

1 Answers1

1

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

Sachin
  • 3,576
  • 1
  • 15
  • 24
  • Sir @SachinKukreja , I guess you are thinking that i am using html
    and
    – Amandeep Singh Dec 04 '18 at 12:33
  • Thanks a lot @SachinKukreja bhai. Finally it solved this problem. – Amandeep Singh Dec 05 '18 at 06:52
  • When I am selecting key i am getting to see that value on server i.e HTTP GET /testPage/value_choices/?key=country . When i chose country i can see options for country in the test_page.html.It means your solution is working perfectly how i wanted to.But now when i am selecting country nothing is happening on the server.There is no GET request.I want to save value of 'key' and its corresponding value in a django model.How can i save these value when i cannot see it on the server. Because at the end i will fetch these values from request in view function.May you please help me @SachinKukreja . – Amandeep Singh Dec 05 '18 at 12:17
  • I think what i need to get on the server is like this. HTTP GET /testPage/value_choices/?key=country&country=India (or whatever country i have chosen). – Amandeep Singh Dec 05 '18 at 12:27
  • That is a separate problem which this solution wont be covering. – Sachin Dec 05 '18 at 15:20