DEV Community

Christian Guzman
Christian Guzman

Posted on

Pinning a Shoutout?!

Working on this 7 team web app Ascent, that helps make everyday tasks at Base Camp faster and easier.

MY TEAM : Shoutouts, we are in charge of making a way where students can be shouted out by other students. Each student has their own shoutouts page with all their shoutouts. A shoutout can be liked and pinned within each student shoutouts page.

I'm going to go over pinning a shoutout.

Models.py

  • This is the model for a pinned shoutout. This OneToOneField is making sure that there can only be one PinnedShoutout per User as well as one PinnedShoutout per Shoutout.
  class PinnedShoutout(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    shoutout = models.OneToOneField(Shoutout, on_delete=models.PROTECT)

Urls.py

  • This url's first argument is the path, second argument is going to be the name of the view that it corresponds with, and the third argument is like giving that view another name to be referred as.
   app_name = "shoutouts"

   urlpatterns = [
   path("pinned/<shoutout_id>", PinShoutout.as_view(), name="pinned")
]

Views.py

  • If this view gets called(a shoutout gets pinned) it gets that shoutouts details redirects to another view, otherwise a shoutout gets created. Then if a shoutout has been pinned already it swaps them out removing the previous shoutout and pinning the new one.
   class PinShoutout(View):
    def post(self, request, shoutout_id):
        user = request.user
        shoutout = get_object_or_404(
            Shoutout, pk=shoutout_id).select_related('shoutout')
        if not hasattr(request.user, "pinnedshoutout"):
            new_pinned = PinnedShoutout.objects.create(
                user=user, shoutout=shoutout)
        else:
            request.user.pinnedshoutout.shoutout = shoutout
            request.user.pinnedshoutout.save()
        return redirect("shoutouts:individual_shoutouts", recipient_id=user.id)

Top comments (1)

Collapse
 
oscar18guzman profile image
Oscar Guzman

Great work!