Search code examples
pythondjangodjango-modelsdjango-formsdjango-smart-selects

Form works in Admin correctly but not in Template


I'm trying to use Django-smart-selects which should allow you to create chained forms.

So I've decided to try it on a simple example before adding to my project. The problem is that it works correctly in Admin but it does not work in template (rendered using view method).

It does not raises any error, but it does not populate Country drop down menu when I choose Continent in continent drop down menu.

Please, note that the problem isn't probably in MODELS.PY since it works correctly in Admin.

There are 3 Locations:

  1. America - NewYork
  2. America - Texas
  3. Africa - Morocco

There are two forms - Continent and Country. If I haven't choose Continent, I'm not able to choose any Country. If I choose America, the second menu is populated with NewYork and Texas, which is correct. This is in Admin. In template, I can choose Continent

Here is the code:

FORMS.PY:

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = ('newcontinent','newcountry',)

VIEWS.PY:

def test(request):
    location_form = LocationForm()
    if request.method=='POST':
        print request.cleaned_data
    return render(request,'test.html', context={'location_form':location_form})

ADMIN.PY:

...
admin.site.register(Continent)
admin.site.register(Country)
admin.site.register(Location)
...

URLS.PY:

...
    url(r'^chaining/', include('smart_selects.urls')),
...

TEST.HTML:

{% extends "base.html" %}

{% block content %}
    <form action="" method="post">{% csrf_token %}
    {{ location_form }}
    </form>
{% endblock %}

MODELS.PY:

class Continent(models.Model):
    name = models.CharField(max_length=40)

    def __str__(self):
        return self.name

class Country(models.Model):
    name = models.CharField(max_length=40)
    continent = models.ForeignKey(Continent)

    def __str__(self):
        return self.name

from smart_selects.db_fields import ChainedForeignKey

class Location(models.Model):
    newcontinent = models.ForeignKey(Continent)
    newcountry = ChainedForeignKey(
        Country, # the model where you're populating your countries from
        chained_field="newcontinent", # the field on your own model that this field links to
        chained_model_field="continent", # the field on Country that corresponds to newcontinent
        show_all=True, # only shows the countries that correspond to the selected continent in newcontinent
    )

Solution

  • You must load the form media in your test.html as {{ form.media }} or for your case {{ location_form.media }} so as to include the javascript/css files.