首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >表单在管理中正确工作,但在模板中不起作用。

表单在管理中正确工作,但在模板中不起作用。
EN

Stack Overflow用户
提问于 2016-04-14 18:20:10
回答 1查看 292关注 0票数 0

我正在尝试使用Django-smart-selects,它应该允许您创建链接的forms

所以,我决定在添加到我的项目之前,先在一个简单的例子上尝试一下。问题是它在Admin中正确工作,但在模板中不工作(使用视图方法呈现)。

它不会引发任何错误,但当我在“大陆下拉菜单”中选择“Country”下拉菜单时,它不会填充Continent下拉菜单。

请注意,这个问题可能不在MODELS.PY中,因为它在Admin中正常工作。

有3个地点:

  1. 美国- NewYork
  2. 美国-得克萨斯
  3. 非洲-摩洛哥

有两种形式--欧洲大陆和国家。如果我没有选择Continent,我就不能选择任何国家。如果我选择美国,第二个菜单是填充NewYork和德州,这是正确的。这是在行政部。在模板中,我可以选择欧洲大陆

以下是代码:

FORMS.PY:

代码语言:javascript
复制
class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = ('newcontinent','newcountry',)

VIEWS.PY:

代码语言:javascript
复制
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:

代码语言:javascript
复制
...
admin.site.register(Continent)
admin.site.register(Country)
admin.site.register(Location)
...

URLS.PY:

代码语言:javascript
复制
...
    url(r'^chaining/', include('smart_selects.urls')),
...

TEST.HTML:

代码语言:javascript
复制
{% extends "base.html" %}

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

MODELS.PY:

代码语言:javascript
复制
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
    )
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-15 10:22:17

必须将test.html中的表单媒体加载为{{ form.media }}或为您的情况加载{ location_form.media },以便包含javascript/css文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36630979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档