Django.fun

Django: Problem deleting an Authenticated User profile

I'm having problems deleting a user, where the authenticated user can delete their own account.

But what happens is that the page just refreshes, in the same template and returning '200 ok from POST'

[06/Aug/2022 11:46:33] "POST /members/profile/ HTTP/1.1" 200 4998

members.views.profiles.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User


@login_required(login_url="/accounts/login/")
def profile(request):
    template_name = "members/profile.html"
    context = {}
    return render(request, template_name, context)


def profile_delete(request, pk):
    user_profile = User.objects.filter(pk=pk)
    template_name = "members/profile_delete.html"
    context = {
                  "user_profile": user_profile,
              },

    if request.method == "POST":
        user_profile.delete()
        return render(request, template_name, context)

    return render(request, template_name, context)

members.urls.py

from django.urls import path
from allauth.account import views as allauth_views
from . import views


app_name = "members"
urlpatterns = [
    path("login/", allauth_views.LoginView.as_view(), name="login"),
    path("logout/", allauth_views.LogoutView.as_view(), name="logout"),
    path("profile/", views.profile, name="profile"),
    path("profile/<int:pk>/delete/", views.profile_delete, name="profile_delete"),
]

profile.html

    <div>
        <form method="POST">
            {% csrf_token %}
            <p>Are you sure you want to delete <strong>{{ user | title }}</strong> ?</p>
            <button class="btn btn-danger" href="{% url 'members:profile_delete' user.pk %}" type="submit">
                Delete
            </button>
        </form>
    </div>

When you're pressing your button the server sends a GET request, try changing the logic in your function, instead of:

if request.method == "POST":

use:

if request.method == "GET":

You should use get_object_or_404 for querying single user's profile and then delete it, currently filter() makes no sense, so:

user_profile=get_object_or_404(User,pk=pk)

Note: you should always return HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general.

Tutorials

Константы Python: Улучшение управляемости вашего кода

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

View all tutorials →