python


following button on site not working


Hey guys I am writing a following system for my site and when I go into the admin page and force the user to follow it works fine but my following button doesnt work, it just refreshes the site and just wondering if anyone could help me with it please. Thanks in advance.
EDITED
this is my html
`<button type="button" class="btn btn-primary btn-lg" href="{% url "accounts:follow" username=object.username%}">
{% if following %}Unfollow{% else %}Follow{% endif %}
</button>`
urls.py
urlpatterns = [
url(r'^profile/(?P<username>[\w.#+-]+)', views.UserDetailView.as_view(), name="viewprofile"),
url(r'^profile/(?P<username>[\w.#+-]+)/follow', views.UserFollowView.as_view(), name="follow"),]
views.py
class UserFollowView(View):
def get(self, request, username, *args, **kwargs):
toggle_user = get_object_or_404(User, username__iexact=username)
if request.user.is_authenticated():
is_following = UserProfile.objects.toggle_follow(request.user, toggle_user)
return redirect("accounts:viewprofile")
models.py
class UserProfileManager(models.Manager):
use_for_related_fields = True
def all(self):
qs = self.get_queryset().all()
try:
if self.instance:
qs = qs.exclude(user=self.instance)
except:
pass
return qs
def toggle_follow(self, user, to_toggle_user):
user_profile, created = UserProfile.objects.get_or_create(user=user)
if to_toggle_user in user_profile.following.all():
user_profile.following.remove(to_toggle_user)
added = False
else:
user_profile.following.add(to_toggle_user)
added = True
return added
def is_following(self, user, followed_by_user):
user_profile, created = UserProfile.objects.get_or_create(user=user)
if created:
return False
if followed_by_user in user_profile.following.all():
return True
return False
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='followed_by')
objects = UserProfileManager()
def __str__(self):
return str(self.following.all().count())
def get_following(self):
users = self.following.all()
return users.exclude(username=self.user.username)
Try adding a '$' to the end of your urls. Django tries to match the urls from first to last, and since your first regular expression matches the url you're trying to visit, it doesn't bother looking further and goes to it. The '$' will end the regular expression.
urls.py
urlpatterns = [
url(r'^profile/(?P<username>[\w.#+-]+)$', views.UserDetailView.as_view(), name="viewprofile"),
url(r'^profile/(?P<username>[\w.#+-]+)/follow$', views.UserFollowView.as_view(), name="follow"),]
If the page "just refreshes", it sounds like the button HTML itself is incorrect. I had this problem yesterday and after an hour of digging into my JS and Python, I realized that a button automatically submits a form on the page unless it is declared with the type "button" like this:
<button type="button" ....>
I would advise you to do an API Call for that rather than reloading the site. Its much more elegant and you will probably do it later anyway.
Button in html:
<Button id="FollowBTN" class="fa fa-check btn btn-success" data-href='/profiles/{{profile_user}}/follow/api/' data-likes='{{ user.userprofile.get_follow_users.count }}' href='/profiles/{{profile_user}}/follow/'> Follow </Button>
JS for Button:
$("#followBTN").click(function(e){
e.preventDefault()
var this_ = $('#followBTN')
var followUrl = this_.attr("data-href")
console.log(followUrl)
if (followUrl){
console.log('data')
$.ajax({
url: followUrl,
method: "GET",
data: {},
success: function(data){
console.log(data)
var newLikes;
if (data.follow){
$(this).addClass('color'); //"color" should be a css class like (.color{color:green;})
} else {
$(this).removeClass('color');
}
}, error: function(error){
console.log(error)
console.log("error1")
}
})
}
})
});
View:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
class PostFollowAPIToggle(APIView):
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get(self, request,username, format=None):
username = self.kwargs.get("username")
user = self.request.user
obj = get_object_or_404(UserProfile, user=user)
url_ = obj.get_absolute_url()
other_user_username = self.kwargs.get("username")
other_user = get_object_or_404(User, username=other_user_username)
updated = False
follow = False
if user.is_authenticated():
if other_user in obj.follow.all():
follow = False
obj.follow.remove(other_user)
else:
follow = True
obj.follow.add(other_user)
updated = True
data = {
"updated": updated,
"follow": follow
}
return Response(data)
Urls:
url(r'^(?P<username>\w+)/follow/api/$', PostFollowAPIToggle.as_view(), name='follow-api-toggle'),
Userprofile Models:
def get_api_follow_url(self):
return reverse ("profiles:follow-api-toggle", kwargs={"user": self.user})
If you have trouble implementing this write me a message. I had a lot of struggle making this work and I would be glad to help somebody doing the same. The API/Ajax Call is much more user-friendly since the site does not load each time...
I hope that helps.

Related Links

Embed matplotlib in PyQt
Odoo - overriding old api method with new api?
Pylint warning - W5304(Missing-Test-Class)
In terms of efficiency/quickly rejecting things, does it matter if your if statements are on the same line?
QComboBox drop-down list adding unnecessary scroll bar
Specify color type for bar graph pylab
prettifying a part of the html doc using beautifulsoup
Django concatenate two querysets for same model
How can I validate input to accept only binary numbers?
Custom route predicates in Pyramid
Why is my query for a structured property failing with BadFilterError?
Simple Audio Units Host to drive an Audio Units Instrument
kivy language cumbersomeness and rationale behind it
detect if variable is of sympy type
Add markers on line plot from another vector
Does asyncio.wait return only after all done_callbacks were called?

Categories

HOME
answer-set-programming
crate
filterrific
jsviews
drupal-7
webrtc
fparsec
formal-verification
ruby-on-rails-3
triggers
nodemailer
contact-form-7
criteria
lagom
cpanel
cs-cart
cloudflare
r-lavaan
uicollectionview
session-timeout
plsqldeveloper
url.action
tarantool
binutils
tampermonkey
geopandas
winscp
multichoiceitems
websauna
canvasjs
node-horseman
pox
pace
xamarin.uitest
axis-labels
declare
freetts
active-model-serializers
linq-to-entities
android-preferences
flex4.5
distributed-transactions
cppunit
apiary
persistent
component-pascal
struts-layout
gce
fontconfig
unity3d-editor
sql-import-wizard
c64
icefaces
spring-repositories
mongo-c-driver
console-redirect
approval-tests
geodjango
matcaffe
uialertview
mptcp
playscape
prezto
debian-based
lines-of-code
jcr-sql2
c++-actor-framework
python-ggplot
cpu-speed
gmaps4rails
microblaze
x-ua-compatible
formvalidation-plugin
system.web
korma
reserved-words
bsod
facebook-chat
java.util.date
osx-snow-leopard
facebook-sdk-3.1
sslexception
.net-cf-3.5
shortcuts
dynamics-ax-2009
pep8
domain-calculus
android-4.0
enumerators
returnurl
n-layer
radchart
cadisplaylink
mpmovieplayer
ninject-extensions
cross-domain-policy
querystringparameter
coff
qtembedded
paintcomponent
dashcode
gethashcode
nvelocity
squeel
out-of-browser
drawtext
querypath
webrat
self-reference
divx
cots

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App