如何在 Django 中点击模态提交表单并保持模态以处理视图功能?

问题描述 投票:0回答:0

我正在学习 Django 并尝试自己克隆 Instagram。

我使用 bootstrap 创建了一个模态,当我点击 Button 触发模态时,myModal 弹出。

有一个 id=follow-form,人们关注他们关注的用户。

当我提交这个表单时,我想在保持模态的同时关注following.user。

我写的代码关闭模态并转到以下用户的个人资料。

我该如何解决?

模型.py

class User(AbstractUser):
    followings = models.ManyToManyField('self', symmetrical=False, related_name='followers')

urls.py

app_name = 'accounts'
urlpatterns = [
    path('profile/<username>/', views.profile, name='profile'),
    path('follow/', views.follow, name='follow'),
]

views.py

def follow(request, user_pk):
    User = get_user_model()
    person = User.objects.get(pk=user_pk)
    if request.user != person:
        if person.followers.filter(pk=request.user.pk).exists():
            person.followers.remove(request.user)
            is_followed = False
        else:
            person.followers.add(request.user)
            is_followed = True
        context = {
            'is_followed': is_followed,
        }
        return JsonResponse(context)
    return redirect('accounts:profile', person.username)

profile.html

    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
      Following {{ person.followings.count }}
    </button>

    <!-- modal -->
    <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">following list</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            {% for following in person.followings.all %}
              <p>
                <a href="{% url 'accounts:profile' following.username %}">{{ following.username }}</a>

                <!-- Follow -->
                <form id="follow-form" data-user-id="{{ person.pk }}">
                  {% csrf_token %}
                  {% if request.user in following.followers.all %}
                    <input type="submit" value="Unfollow" class="btn btn-primary">
                  {% else %}
                    <input type="submit" value="Follow" class="btn btn-primary">
                  {% endif %}
                </form>

              </p>
            {% endfor %}
          </div>
        </div>
      </div>
    </div>

JS

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
    const form = document.querySelector('#follow-form')
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value
    form.addEventListener('submit', function (event) {
      event.preventDefault()

      const userId = event.target.dataset.userId

      axios({
        method: 'post',
        url: `/accounts/${userId}/follow/`,
        headers: {'X-CSRFToken': csrftoken},
      })
        .then((response) => {
          console.log(response.data)
          const isFollowed = response.data.is_followed
          const followBtn = document.querySelector('#follow-form > input[type=submit]')
          if (isFollowed === true) {
            followBtn.value = 'Unfollow'
          } else {
            followBtn.value = 'Follw'
          }
        })
    })
    </script>

当我提交这个表单时,我想在保持模态的同时关注following.user。

javascript python django ajax axios
© www.soinside.com 2019 - 2024. All rights reserved.