首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我使用django-smart-selects的方式有问题吗?为什么我不能制作ModelForm?

我使用django-smart-selects的方式有问题吗?为什么我不能制作ModelForm?
EN

Stack Overflow用户
提问于 2017-04-09 17:14:44
回答 1查看 281关注 0票数 0

我使用的是django-smart-select。我想为我的位置模型,允许选择大陆上的国家将出现的表单。提供用户地址后,需要提交表单。这就是我所做的。

代码语言:javascript
复制
 # 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,但没有帮助,同样的结果也出现了。

EN

回答 1

Stack Overflow用户

发布于 2017-04-24 20:12:57

您的代码看起来很好。签入你的管理页面。如果智能选择在管理页面中工作,那么在您的html文件中包括以下内容:顺序重要。

代码语言:javascript
复制
        <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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43305038

复制
相关文章

相似问题

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