Bindu Machani
Bindu Machani

Reputation: 71

Delete the particular user without using admin panel in django

I have created my models using django user model. I am able to perform the edit functionality to the created form.Now i want to do DELETE the particular user details by using DELETE button.Here is my code

models.py

from django.db import models
from django.contrib.auth.models import User


class UserProfileInfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username

forms.py

class EditProfileForm(forms.ModelForm):
    class Meta():
        model = User
        fields = ['first_name','last_name','username','email','password']
        help_texts={
            'username': None
        }

views.py

 def delete_profile(request, id):
    profile = UserProfileInfo.objects.filter(id=id)
    if request.method == 'POST':
        profile.delete()
        return HttpResponseRedirect(reverse('signupapp:index'))
    return render(request, "signupapp/delete_profile.html", {'profile': profile})

delete_profile.html

    <form action="" method ="POST">
    {% csrf_token %}
    <p>Are you sure to delete "{{UserProfileInfo.username}}"?</p>
    <input type="submit" value="Delete"/>
</form>

Delete button link

index.html

<a href="{% url 'signupapp:delete' request.user.id %}"><input type="button" value="Delete"/></a><br>

When i run this code it is working.But the user I am deleting is not deleting in the database.

Can anyone help me to clear it. Thanks in advance..

Upvotes: 1

Views: 579

Answers (1)

rahul.m
rahul.m

Reputation: 5854

You are using auth user id to delete user profile id

try this

from django.contrib.auth.models import User
def delete_profile(request, id):  --> id : is auth user id
    user = User.objects.get(id=id)
    profile = UserProfileInfo.objects.filter(user=user)
    if request.method == 'POST':
        profile.delete()
        User.objects.filter(id=id).delete()

Upvotes: 1

Related Questions