'How to add a object to a users watch list via a link in Django
I have a website that recommends anime and I want each anime to have some text besides them as they appear, offering to add to a users 'list' which is a page where all anime in the users account-unique list will be shown. I have it working, and can add via the django admin but not via a button on the website.
models.py
class UserList(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
anime_in_list = models.ManyToManyField(Anime, blank=True)
views.py
@login_required
def userList(request):
return render(request, 'userlist.html')
def add_to_userlist(request, anime_id):
new_anime = get_object_or_404(Anime, pk=anime_id)
#if UserList.objects.filter(user=request.user, anime_in_list=anime_id).exists():
#message fail
user_list, created = UserList.objects.get_or_create(user=request.user)
user_list.anime_in_list.add(new_anime)
return render(request, "userlist.html")
on the html where the anime shows
<a href="{% url 'add_to_userlist' anime.id %}" role="button" class="btn btn-outline-success btn-lg">Add to list?</a>
urls.py
urlpatterns = [
...
path('userlist/', user_views.userList, name='userlist'),
path('anime/', AnimeListView.as_view(), name='all-anime'),
...
]
but navigating to the anime html page now the error NoReverseMatch at /anime/ Reverse for 'add_to_userlist' not found. 'add_to_userlist' is not a valid view function or pattern name.
But I don't want to create a separate url to redirect them, I just want pressing the to add to the users list, and if the user now navigates to their /userlist, they find that it has updated with the anime they clicked the link on.
Essentially it could be thought of like a shopping cart, where products exist and I just want to be able to click on them to add them to my list that works with the way I have models.py. Any help would be super appreciated, ty
Solution 1:[1]
I am not an expert, but you can try to return an empty HttpResponse
from django.http import HttpResponse
return HttpResponse('')
and on client side do a AJAX call to that view. Look Here
or even better return a json which has included information about the proccess was succesfully or not and handle that result correctly on js side.
from django.http import JsonResponse
return JsonResponse({'status':'Anime already added'})
Needs JQuery
$.getJSON( "<django view url>", function(data) {
console.log( "success" );
}).done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
