我使用的是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,但没有帮助,同样的结果也出现了。
发布于 2017-04-24 20:12:57
您的代码看起来很好。签入你的管理页面。如果智能选择在管理页面中工作,那么在您的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>https://stackoverflow.com/questions/43305038
复制相似问题