2017-04-09 4 views
0

私はdjango-smart-selectを使用しています。私は、国が現れる大陸の選択を可能にする私のロケーションモデルのためのフォームが必要です。ユーザーのアドレスを入力したら、フォームを提出する必要があります。これは私がやったことです。django-smart-selectを使っているときに何か問題がありますか?なぜ私はModelFormを作成できませんか?

# 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

コードは正常です。 管理ページにチェックインしてください。スマートセレクトが管理ページで機能している場合は、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> 
関連する問題