Reputation: 13
In my project, I have 2 models Article and Quote. Every time, a user click a button in the home page, it will add the related quote into user's article.
The Article.models look like this:
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
Here is the 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 »</a></p>
It does work. However, it also reloads home page. So when I scroll down and click the button, the page goes back to the top and doesnt stay where i click.
I did some research finding out that dajax might help but just have no idea how to solve my problem with it or another efficient way?
Upvotes: 1
Views: 176
Reputation:
There are two ways to go about this, and I recommend you implement them both.
Include anchors for each quote, so when you redirect you can redirect like so:
HttpResponseRedirect(reverse("home")+"#quote_id_%s"%(q.id))
Which will look like:
http:example.com#quote_id_123
And jumps to the element with that id, like:
<blockquote id="quote_id_123">Four score and seven years ago...</blockquote>
This means that users who don't have Javascript (which is still a surprising amount) get the functionality of jumping to the right location.
To do this you can alter your for loop like so:
{% 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 %}
This is less straight-forward, and will require writing a lot more code than above, but basically will require submitting the form via some ajax method, capturing the response (or error) correctly, and updating the page.
Dajax and jQuery will probably help in this regard, but will be very specific to your site.
Upvotes: 1