2015-02-06 42 views
1

在我的項目中,我有2個模型文章和報價。每次用戶點擊主頁上的一個按鈕,它都會將相關的報價添加到用戶的文章中。如何在不重新加載的情況下將其返回主頁

的Article.models是這樣的:

class Article(models.Model): 
    user = models.OneToOneField(User, null=True) 
    quote = models.ManyToManyField(Quote, blank=True, null=True) 
    def __unicode__(self): 
     return self.user.username 

這裏是view.py

def add_quote(request, id): 
    u = User.objects.get(username=request.user) 
     a = Article.objects.get(user=u) 
    q = Quote.objects.get(id=id) 
    a.quote.add(q) 
    a.save() 

    return HttpResponseRedirect(reverse("home")) 

的Home.html:

{% for quote in quotes %} 
<p>{{ quote.description }}</p> 
<p><a class="btn btn-primary" href="{{ quote.get_absolute_url }}" 
role="button" data-container="body" data-toggle="popover" 
data-placement="top" data-content="added">collect &raquo;</a></p> 

它的工作。但是,它也會重新加載主頁。所以當我向下滾動並點擊按鈕時,頁面會回到頂部,並且不會保留在我點擊的位置。

我做了一些研究發現,dajax可能會幫助,但不知道如何解決我的問題或其他有效的方式嗎?

回答

1

有兩種方法可以解決這個問題,我建議你兩種方法來實現它們。

1.無Javascript方法。

包括每個報價錨,所以當你重定向,你可以像這樣重定向:

HttpResponseRedirect(reverse("home")+"#quote_id_%s"%(q.id)) 

這將是這樣的:

http:example.com#quote_id_123 

,並跳轉到該ID,如元素:

<blockquote id="quote_id_123">Four score and seven years ago...</blockquote> 

這意味着,沒有Javascript(這仍然是一個驚人的數量)的用戶得到跳到正確位置的功能。

要做到這一點,你可以改變你的for循環,像這樣:

{% for quote in quotes %} 
    <p id="quote_id_{{quote.id}}">{{ quote.description }}</p> 
    <p><a class="btn btn-primary" href="{{ quote.get_absolute_url }}" 
    <!-- etc ... --> 
{% endfor %} 

2.使用漸進增強添加的Javascript

這是不太直接的,並且需要編寫大量的代碼更比上面要多,但基本上需要通過一些Ajax方法提交表單,正確捕獲響應(或錯誤),並更新頁面。

Dajax和jQuery可能會在這方面提供幫助,但會對您的網站非常具體。

+0

非常感謝Sam。第一種方法工作得很好。請問你能告訴我更多關於第二種方法的信息嗎? – Leonsion 2015-02-06 09:09:21

相關問題