我正在使用django-smart-select。我想要一个我的位置模型的表单,它允许根据国家将出现的大陆进行选择。提供用户地址后,需要提交表单。这就是我所做的。
# myapp/models.py
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
class Continent(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length=20)
continent = models.ForeignKey(Continent)
def __str__(self):
return self.name
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=False, # only shows the countries that correspond to the selected continent in newcontinent
)
my_address = models.CharField(max_length=20)
#myapp/forms.py
from myapp.models import Location
from django.forms import ModelForm
class LocationForm(ModelForm):
class Meta:
model = Location
fields = ['newcontinent', 'newcountry', 'my_address']
#myapp/templates/myapp/addLocationForm.html
{% extends 'registration/base.html' %}
{% block title %}Add a new location{% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit"> Post </button>
</form>
{% endblock %}
#myapp/views.py
def addlocation(request):
if request.POST == "POST":
form = LocationForm()
if form.is_valid():
form.save()
return redirect('home')
else:
form = LocationForm()
return render(request, 'myapp/addLocationForm.html', { 'form': form})
#urls.py
url(r'^location/add/$', core_views.addlocation,name='add-location'),
上述代码不起作用。我可以选择由管理员添加的大陆。但是,没有选择国家的选项。
我也尝试使用没有帮助的通用CreatView,并且出现了相同的结果。
答案 0 :(得分:0)
您的代码看起来很好。 检查您的管理页面。如果智能选择在管理页面中有效,那么在您的html文件中包含以下内容:顺序很重要。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js</script>
<script src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script>
<script src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script>