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.