Reputation: 147
I would like to remove user.
I know that probably I can use some library like allauth but I want to do this on my view. I didn't find any tutorial for that so I am trying to do this learn-by-mistakes way.
Ok. so in urls I have:
urlpatterns = [
('^remove$', views.remove_user, name="remove"),
]
forms:
class RemoveUser(forms.ModelForm):
class Meta:
model = User
fields = ('username',)
views:
@login_required(login_url='http://127.0.0.1:8000/')
def remove_user(request):
if request.method == 'POST':
form = RemoveUser(request.POST)
username = request.POST.get('username')
if form.is_valid():
rem = User.objects.get(username=username)
rem.delete()
return redirect('main')
else:
form = RemoveUser()
context = {'form': form}
return render(request, 'remove_user.html', context)
I can access website and type text in textfield. When I type random username I get error "user does not exist" so everything ok, but when I type correct username I get message: "A user with that username already exists" and this user is not removed.
Please, can you help me with that?
Upvotes: 0
Views: 5622
Reputation: 2817
Change your form to a normal form-
class RemoveUser(forms.Form):
username = forms.CharField()
The view will be as follows -
@login_required(login_url='http://127.0.0.1:8000/')
def remove_user(request):
if request.method == 'POST':
form = RemoveUser(request.POST)
if form.is_valid():
rem = User.objects.get(username=form.cleaned_data['username'])
if rem is not None:
rem.delete()
return redirect('main')
else:
## Send some error messgae
else:
form = RemoveUser()
context = {'form': form}
return render(request, 'remove_user.html', context)
EDIT-- Another way to approach the same problem is to deactivate the user
if form.is_valid():
rem = User.objects.get(username=form.cleaned_data['username'])
if rem is not None:
rem.is_active = False
rem.save()
Upvotes: 5