Home > database >  Django: Problem deleting an Authenticated User profile
Django: Problem deleting an Authenticated User profile

Time:08-07

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  href="{% url 'members:profile_delete' user.pk %}" type="submit">
                Delete
            </button>
        </form>
    </div>

CodePudding user response:

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":

CodePudding user response:

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.

  • Related