我希望有一个选择框(下拉列表)State
,其中包含一些选项,例如:
VIC
NSW
SA
...
然后在我的forms.py中有一个字段,例如City
(这是一个站点名称),例如:
Melbourne
Sydney
我对Django很陌生,所以请记住这一点,抱歉。
我现在没有在一个关键的项目或任何事情上工作,只是想学习Django,所以如果我需要创建一个新项目,那就没什么大不了的了。
我猜是某种javascript或者可能需要动态更新City
表单字段?
提前致谢。
编辑: 我的意思就像一个测试项目,对不起应该更清楚,这就是我现在所拥有的:
例如,如果我选择NSW,悉尼,那么地址= 10悉尼路(所以我想要字段Address
= "10 Sydney Road"
forms.py:
STATE_CHOICES = (
('NSW', 'VIC', '...'),
)
CITY_CHOICES = (
('Sydney', 'Melbourne', '...'),
)
models.py:
state = models.CharField(max_length=200, choices=STATE_CHOICES)
city = models.CharField(max_length=200, choices=CITY_CHOICES)
address = models.CharField(max_length=200, blank=True)
views.py:
@login_required
def configs_edit(request, pk):
configs = get_object_or_404(Configurations, pk=pk)
if request.method == "POST":
form = ConfigsForm(request.POST, instance=configs)
if form.is_valid():
configs = form.save(commit=False)
configs.author = request.user
configs.save()
return redirect('configs_detail', pk=configs.pk)
else:
form = ConfigsForm(instance=configs)
return render(request, 'blah/configs_edit.html', {'form': form})
urls.py:
url(r'^configs/(?P<pk>[0-9]+)/edit/$', views.configs_edit, name='configs_edit'),
template:
{% extends "blah/base.html" %}
{% block content %}
<h1>New Configuration</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
答案 0 :(得分:0)
您应该使用JavaScript,请参阅onchange
事件。 Rembember仍然需要在服务器端执行验证。
答案 1 :(得分:0)
我自己解决了这个问题:
我手动填充表单:
template:
<div>
STATE: {{ form.state }}
</div>
<div>
CITY: {{ form.city }}
</div>
<div>
ADDRESS: {{ form.Address }}
</div>
<script>
$(document).ready(function(){
$('#id_state').change(function() {
var selected = $(this).val();
if(selected == 'VIC') {
$('#id_Address').val('10 Melbourne Street');
# - to fill in more than one field: $('#id_blah').val('other val');
}
else if(selected == 'WA') {
$('#id_Address').val('10 West Australia Street');
}
else if(selected == 'SA') {
$('#id_Address').val('10 South Australia Street');
}
else if(selected == 'NSW') {
$('#id_Address').val('Sydney');
}
else if(selected == 'QLD') {
$('#id_Address').val('10 Queensland Street');
}
});
});
</script>
choices.py:
STATE_CHOICES = (
('NSW', ("NSW")),
('VIC', ("VIC")),
('SA', ("SA")),
('WA', ("WA")),
('QLD', ("QLD"))
)
CITY_CHOICES = (
('Sydney', ("Sydney")),
('Melbourne', ("Melbourne"))
)