尝试在this example之后完成一个相当简单的链式选择。 这是我能找到的最适合我有限要求的例子,并认为它只需要一些重命名来匹配我的设置。
models.py
class Category(models.Model):
"""Category"""
name = models.CharField(max_length=50)
slug = models.SlugField()
def save(self, *args, **kwargs):
# Uncomment if you don't want the slug to change every time the name changes
#if self.id is None:
#self.slug = slugify(self.name)
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
# return u'%s' % (self.name)
class SubCategory(models.Model):
"""Sub Category"""
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
slug = models.SlugField()
def save(self, *args, **kwargs):
# Uncomment if you don't want the slug to change every time the name changes
#if self.id is None:
#self.slug = slugify(self.name)
self.slug = slugify(self.name)
super(SubCategory, self).save(*args, **kwargs)
def __unicode__(self):
# return self.name
return u'%s' % (self.name)
class Website(models.Model):
""" service website."""
url = models.URLField(validators=[validate_onion_url], unique=True)
# service
id = models.CharField(primary_key=True, max_length=16,
validators=[MinLengthValidator(16), MaxLengthValidator(16)], unique=True)
#is this domain banned
banned = models.BooleanField(default=False)
#is it online or offline
online = models.BooleanField(default=False)
#echo -e "BLAHBLAHBLAH.onion\c" | md5sum
#hashlib.md5(url[8:-1]).hexdigest()
md5 = models.CharField(max_length=32,
validators=[MinLengthValidator(32), MaxLengthValidator(32)], unique=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=True)
sub_categories = models.ForeignKey(SubCategory, default=1)
referral = models.TextField(blank=True)
class Meta:
"""Meta class."""
app_label = 'ahmia'
def __unicode__(self):
# return self.url
return u'%s' % (self.url)
和views.py
@require_GET
def category_browser(request):
"""Browser Page"""
categories = Category.objects.all().prefetch_related('subcategory_set')
subcategories = SubCategory.objects.filter(category=categories)
return render(request, 'browser.html', {'categories': categories, 'subcategories': subcategories)
def getdetails(request):
#country_name = request.POST['country_name']
subcategory_name = request.GET['cnt']
print "ajax subcategory_name ", subcategory_name
result_set = []
all_websites = []
answer = str(subcategory_name[1:-1])
selected_subcategory = SubCategory.objects.get(name=answer)
print "selected subcategory name ", selected_subcategory
all_websites = selected_subcategory.website_set.all()
for website in all_websites:
print "website name", website.url
result_set.append({'name': website.url})
return HttpResponse(simplejson.dumps(result_set), mimetype='application/json', content_type='application/json')
和html模板
<html>
<head>
<script type="text/javascript" src="/static/js/jquery-latest.min.js"></script>
<script type="text/javascript" src="/static/js/script.js"></script>
<script>
$(document).ready(function(){
$('select#selectsubcategories').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var subcategory_name = optionSelected.text();
data = {'cnt' : subcategory_name };
ajax('/getdetails',data,function(result){
console.log(result);
$("#selectwebsites option").remove();
for (var i = result.length - 1; i >= 0; i--) {
$("#selectwebsites").append('<option>'+ result[i].url +'</option>');
};
});
});
});
</script>
</head>
<body>
<select name="selectsubcategories" id="selectsubcategories">
<option value="" selected="selected">Select Category</option>
{% for category in categories %}
<optgroup label="{{ category.name }}">
{% for item in category.subcategory_set.all %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</optgroup>
{% endfor %}
</select>
<select name ="selectwebsites" id="selectwebsites">
</select>
</body>
</html>
显示类别/子类别的第一个选择框按预期工作,但无论选择哪个子类别,第二个选择框都保持为空。
没有我能看到的错误,也不知道如何调试它。
我假设所遵循的示例是一个非常好的工作解决方案,我怀疑问题是在我的命名方案中的某处,例如我在引用我的外键时把某个子类别和sub_category混在一起? 但我可能错了,
很有必要!编辑:
发现错误,在我的http日志中,我可以看到对/ getdetails的调用,这是有道理的。 但是在urls.py中添加/ getdetails后,我的http日志中仍然出现500错误
# Browser Page
urlpatterns += patterns('',
(r'^browser/', 'rango.views.category_browser'),
(r'^getdetails/', 'rango.views.getdetails'),
)
答案 0 :(得分:0)
将/ getdetails添加到url.py可以解决部分问题,原始示例中没有提到。
dd($game)
并从views.py
中删除# Browser Page
urlpatterns += patterns('',
(r'^browser/', 'rango.views.category_browser'),
(r'^getdetails/', 'rango.views.getdetails'),
)
因为这在django 1.7中贬值似乎