1

I have a model and a form like this:

class MyModel(models.Model):
    param = models.CharField()
    param1 = models.CharField()
    param2 = models.CharField()

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('param', 'param1', 'param2')

Then I have one drop down menu with different values and based on what value is selected I'm hiding and showing fields of MyForm. Now I have to take one step further and render param2 as a CheckboxInput widget if user selects a certain value from a drop down but in other cases it should be standard text field. So how would I do that?

ragezor
  • 360
  • 1
  • 4
  • 16
  • 2
    Have you tried using Javascript? – Paul Collingwood Mar 25 '14 at 12:33
  • I don't want to hack something like this in Javascript because the whole point of Django forms is that they are rendered for you. I was thinking more in lines of creating multiple forms on the MyModel and then showing/hiding them with Javascript. But how would I then control from which form I actually get the data? – ragezor Mar 25 '14 at 12:37
  • Django can render forms for you, but it doesn't have a built-in mechanism to change the field type on the client side. JavaScript is really your best option in this case, imo. – Brandon Taylor Mar 25 '14 at 12:40

2 Answers2

4

I know this post is almost a year old, but it took me multiple hours to even find a post related to this topic (this is the only one I found, which came up as related when submitting my own question), so I felt the need to share my solution.

I wanted to have a form that would show and require a text field if an option from a dropdown menu matched a value stored in another model. I had a foreignKey relation between two models and I passed an instance of Model1 into the ModelForm for Model2. If a value chosen for a variable in Model2 matched a variable already set in Model1, I wanted to show and require a textfield. It was basically a "choose Other and then enter your own description" scenario.

I did not want the page to reload (I was trying to have this work in both mobile and desktop browsers with the least delay/reloads and using the same code for both), so I could not use the mentioned multiple forms loading in a view option. I started trying to do it with AJAX as suggested above when I realized I was over thinking the problem.

The answer was using JS and clean methods in the form. I added a non-required field (field1) that was not in Model2 to my Model2Form. I then hid this using jQuery and only displayed it (using jQuery) if the value of another field (field2) matched the value of the variable from Model1. To make that work, I did decide to have a hidden < span > in my template with the pk of the variable so I could easily grab it with jQuery. This jQuery worked perfectly for hiding and showing the field correctly so the user could choose the "other" value and then decided to choose a different one instead (and go back and forth endlessly).

I then used a clean method in my Model2Form for field1 that raised a ValidationError if no value was entered when the value in field2 matched my Model1 variable. I accessed that variable by using "self.other = Model1.variable" in my __ init __ method and then referencing that in the clean_field1 method.

I would have liked to have been able to accomplish this without having to hide and show a field with JS, but I think the only solutions for doing so with views or ajax caused delays/reloads that I did not want. Also, I liked the general simplicity of the method I used, rather than having to figure out how to pass partial forms back and forth through the HTTPRequest.

Update:
In my situation, I was creating entries for lost and found items and if the location where the item was found was not a provided option, then I wanted to show a textbox for the user to enter the location. I created a location object that was set as the "other" location and then displayed the textbox when that object was selected as the "found" location.

In forms.py, I added an extra CharField and use a clean method to check if the field is required and then throw a ValidationError if it wasn't filled in:

class Model2Form(forms.ModelForm):
    def __init__(self, Model1, *args, **kwargs):
        self.other = Model1.otherLocation
        super(Model2Form, self).__init__(*args, **kwargs)
        ...

    otherLocation = forms.CharField(
        label="Location Description",
        max_length=255,
        required=False
    )

    def clean_otherLocation(self):
        if self.cleaned_data['locationFound'] == self.other and not self.cleaned_data['otherLocation']:
            raise ValidationError("Must describe the location.")
        return self.cleaned_data['otherLocation']

Then in my JavaScript, I checked if the value of the "found" location was the "other" location (the value of which I had in a hidden span on my html page). I then used .show() and .hide() on the textbox's parent element as necessary:

$("#id_locationFound").change( function(){
    if ($("#id_locationFound").val() == $("#otherLocation").attr("value")){ //if matches "other" location, display textbox; otherwise, hide textbox
        $("#id_otherLocation").parent().show();
    }else
        $("#id_otherLocation").parent().hide();
});
mattarchie
  • 63
  • 6
  • I included some code snippets to show what I was talking about, sorry the original was so abstract without example code. – mattarchie Oct 15 '15 at 00:05
0

Your best guess would be to trigger a "POST" request when you select something from your drop down menu.

The Value of that "POST" has to correspond your values you use to determine which field you would like to output.

Now you will actually need two forms:

class MyBaseForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('param', 'param1', 'param2')

class MyDropDownForm(MyBaseForm):
    class Meta:
        widgets = {
            'param2': Select(attrs={...}),
        }

So as you can see the DropDownForm has been derived from MyBaseForm to make sure it will have all the same properties. But we have modified the widget of one of the fields.

Now you can update your view. Please note, this is untested Python + Pseudocode

views.py

def myFormView(request):
  if request.method == 'POST': # If the form has been submitted...    
    form = MyBaseForm(request.POST)

    #submit button has not been pressed, so the dropdown has triggered the submission. 
    #Hence we won't safe the form, but reload it            
    if 'my_real_submitbotton' not in form.data:     

      if 'param1' == "Dropdown":
         form = MyDropDownForm(request.POST)

    else:
      #do your normal form saving procedure
  else:
    form = ContactForm() # An unbound form

  return render(request, 'yourTemplate.html', {
    'form': form,
  })

This mechanism does the following: When the form is submitted it checks if you have pressed the "submit" button or have used a dropdown onChange to trigger a submission. My solution doesn't contain the javascript code you need to trigger the submission with an onChange. I just like to provide a way to solve it. To use the 'my_real_submitbutton' in form.data construct you will be required to name your submit button:

<input type="submit" name="my_real_submitbutton" value="Submit" />

Of course you can choose any string as Name. :-)

In case of a submit by your dropdown field you must check which value has been selected in this drop down menu. If this value satisfies the condition you want to return a Dropdown Menu you create an instance of DropDownForm(request.POST) otherwise you can leave everything as it is and rerender your template.

On the downside this will refresh your page. On the upside it will keep all the already entered field values. So no harm done here.

If you would like to avoid the page refresh you can keep my proposed idea but you need to render the new form via AJAX.

Dr.Elch
  • 2,105
  • 2
  • 17
  • 23