Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Forms and Favorites Functionality

Forms and Favorites Functionality

In this chapter you will learn to handle user POST requests, establish many-to-many relationships, and implement the "favorite article" feature.


Data model design for the favorites feature

The core of the favorites feature is: one user can favorite multiple articles, and one article can be favorited by multiple users.

This is a typical many-to-many (ManyToMany) relationship.

We do not need to create a new model—Django's User model is built-in; we only need to add a ManyToManyField in the Post model pointing to User.

Example

File path: add to the Post class in blog/models.py

from

django.

contrib

.

auth

.

models

import

User

class

Post

(

models.

Model

)

:

   

... existing fields ...

   

Favorited by: ManyToManyField automatically creates an intermediate table

    favorites

=

models.

ManyToManyField

(

        User

,

        related_name

=

'favorite_posts'

,

 

Reverse query: user.favorite_posts.all()

        verbose_name

=

'favorited by'

,

        blank

=

True

   

)

After modifying the model, generate and execute the migrations:



(venv) $ python manage.py makemigrations

(venv) $ python manage.py migrate


View logic for favoriting and unfavoriting

Example

File path: blog/views.py, newly added

from

django.

shortcuts

import

render

,

redirect

,

get_object_or_404

from

django.

contrib

.

auth

.

decorators

import

login_required

from

django.

contrib

import

messages

from

.

models

import

Post

login_required decorator: when a logged-out user accesses this view, automatically redirect to the login page

@

login_required

def

toggle_favorite

(

request

,

pk

)

:

   

"""Toggle favorite status: favorited → unfavorite, not favorited → favorite"""

    post

=

get_object_or_404

(

Post

,

pk

=

pk

)

   

Check whether the current user has favorited

   

if

post.

favorites

.

filter

(

id

=

request.

user

.

id

)

.

exists

(

)

:

       

Favorited → unfavorite

        post.

favorites

.

remove

(

request.

user

)

        messages.

info

(

request

,

f

'Unfavorited "{post.title}"'

)

   

else

:

       

Not favorited → add to favorites

        post.

favorites

.

add

(

request.

user

)

        messages.

success

(

request

,

f

'Favorited "{post.title}"'

)

   

Redirect back to the current page (HTTP_REFERER is the URL of the source page)

    referer

=

request.

META

.

get

(

'HTTP_REFERER'

,

'/'

)

   

return

redirect

(

referer

)

ManyToMany operation method quick reference

Method Purpose Example
add(obj) Add association post.favorites.add(user)
remove(obj) Remove association post.favorites.remove(user)
all() Query all associated objects post.favorites.all()
filter(...) Filter with conditions post.favorites.filter(id=1)
exists() Determine whether there are matching records post.favorites.filter(id=1).exists()
clear() Clear all associations post.favorites.clear()

Configure favorite routes

Example

File path: append to blog/urls.py

urlpatterns

=

[

   

... existing routes ...

    path

(

'post/int:pk/favorite/'

,

views.

toggle_favorite

,

name

=

'toggle_favorite'

)

,

]


Add a favorite button on the detail page

Example

{% extends 'blog/base.html' %}

{% block title %}{{ post.title }} - RUNOOB Blog{% endblock %}

{% block content %}

   

{{ post.category.name }}

   

       

{{ post.title }}

       

        {% if user.is_authenticated %}

       

            {% csrf_token %}

           

       

        {% endif %}

   

   

   

{{ post.content|safe }}

   

← Back to Home

{% endblock %}

Also add a favorite button to the article cards on the homepage:

Example

   

       

{{ post.category.name }}

       

{{ post.title }}

       

{{ post.summary|truncatechars:80 }}

       

   

Why use a form instead of an a tag for the favorite button? Because the favorite operation modifies the database and is a POST request. According to REST conventions, read operations use GET and write operations use POST. More importantly, POST requests carry csrf_token, preventing malicious websites from forging requests.


Favorites list page

Display the list of favorited articles for logged-in users.

Example

File path: blog/views.py, newly added

@

login_required

def

favorites

(

request

)

:

   

"""Current user's favorites list"""

   

Reverse query the user's favorited articles via related_name

    posts

=

request.

user

.

favorite_posts

.

all

(

)

.

order_by

(

'-created_at'

)

   

return

render

(

request

,

'blog/favorites.html'

,

{

       

'posts'

: posts

,

       

'title'

:

'My Favorites - RUNOOB Blog'

   

}

)

Add a route in urls.py and a "My Favorites" link in the navigation bar.


Favorite button styles

Example

/* append to the style in base.html */

.post-header

{

   

display

:

flex

;

   

justify-content

:

space-between

;

   

align-items

:

flex-start

;

}

.fav-btn

,

.fav-btn-small

{

   

background

:

none

;

   

border

:

none

;

   

font-size

:

18px

;

   

cursor

:

pointer

;

   

color

:

#e74c3c

;

   

padding

:

4px

8px

;

    transition

:

transform 0.2s

;

}

.fav-btn

:hover

,

.fav-btn-small

:hover

{

    transform

:

scale

(

1.2

)

;

}

.fav-btn-small

{

   

font-size

:

16px

;

}

.fav-form

{

   

display

:

inline

;

}

.card-footer

{

   

display

:

flex

;

   

justify-content

:

space-between

;

   

align-items

:

center

;

   

margin-top

:

10px

;

}


Chapter Summary

In this chapter you mastered user interaction handling in Django: ManyToManyField for many-to-many relationships, POST requests for form handling, csrf_token security protection, the login_required decorator to protect views, and request.user to determine the current user's identity.

The favorites feature lets users mark articles they like and view them in their personal favorites list.