2016-02-19 129 views
0

試圖完成一個相當簡單的鏈接選擇this example。 這是我能找到的最適合我的有限需求的例子,並且認爲它只需要一些重命名來匹配我的設置。django鏈接選擇框

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> 

作品如預期顯示類別/子類別的第一個選擇框,但是第二個選擇框保持空白,無論選擇哪個子類別。

沒有錯誤,我可以看到,不知道如何調試。

我假設接下來的例子是一個完美的工作解決方案,我懷疑問題在我的命名方案的某個地方,例如我是否在引用我的外鍵時在某個地方混合了子類別和子類別? 但我可能是錯的,

非常感謝!

編輯:

發現錯誤,在我的HTTP日誌中我可以看到一個呼叫到/ getdetails取得,是有道理的。 將在urls.py/getdetails後,但是我仍然可以在我的HTTP 500錯誤日誌

# Browser Page 
urlpatterns += patterns('', 
    (r'^browser/', 'rango.views.category_browser'), 
    (r'^getdetails/', 'rango.views.getdetails'), 
) 

回答

0

抱歉這麼快回答我的問題後,

添加/ getdetails到url.py解決部分這個問題在最初的例子中沒有提到。

# Browser Page 
urlpatterns += patterns('', 
    (r'^browser/', 'rango.views.category_browser'), 
    (r'^getdetails/', 'rango.views.getdetails'), 
) 

和views.py

mimetype='application/json', 

,因爲這去除在Django 1.7折舊似乎