Hello!
I am trying to implement a like function and encountered an error I can’t get my head around. I appreciate all guidance and explanations.
Problem:
- I cannot render the profile page. Whenever I render the profile page I get an NoReversMatch error.
- The context_object_name dosen’t work. I am using object.something in my template to display data. The numer of likes is displayed without a problem.
In the model, I have both a OneToOne and a ManyToMany relationship to the Member model. I does not make sense to me having the two relationships because they to seem to contradict each other. Can someone explain if this is correct or not?
What I have done
I’ve made sure that there is data in the database.
View:
class ProfilePageView(DetailView):
model = ProfilePageMember
template_name = "profile_app/profilepage.html"
# context_object_name = "user_data"
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
stuff = get_object_or_404(ProfilePageMember, id=self.kwargs["pk"])
total_likes = stuff.total_likes()
context["total_likes"] = total_likes
return context
def LikeView(request, pk):
profile = get_object_or_404(
ProfilePageMember, id=request.POST.get("profile_likes"))
profile.likes.add(request.user)
return HttpResponseRedirect(reverse("profilepage_app:profile-redirect", args=[str(pk)]))
Model
class ProfilePageMember(models.Model):
members = models.OneToOneField(Member, on_delete=models.CASCADE)
likes = models.ManyToManyField(Member, related_name="profile_likes")
def __str__(self):
return str(self.members)
def total_likes(self):
return self.likes.count()
URL
urlpatterns = [
path("profilsida/<int:pk>/",
views.ProfilePageView.as_view(), name="profile-redirect"),
path("uppdatera-profil/<int:pk>/", views.ProfilePageUpdateView.as_view(),
name="profilepage-update"),
path("likes/<int:pk>/", views.LikeView, name="profile_likes"),
[
Template
<div class="d-flex align-items-center justify-content-between flex-row">
<form action="{% url 'profilepage_app:profile_likes' profile.pk %}" method = "POST">
{% csrf_token %}
<input type="submit" name="profile_likes" value="{{profile.id}}">
<i class="bi bi-hand-thumbs-up"></i>
</input>
</form>
</div>