#Is there anyway to deactivate selected user when I was logged in as superuser on webpage.

38 messages · Page 1 of 1 (latest)

restive phoenix
#

We can use the admin panel provided by django to deactivate selected user when we logged in as superuser. I want to know is there anyway to do this action in my webpage instead of using the admin panel. For example, I selected a user “Jack” and click a button “deactivate” then the account of “Jack” is deactivated. He cannot login anymore until I active his account. Thank you🙏🏻

#

Is there anyway to deactivate selected user when I was logged in as superuser on webpage.

tame prism
#

All that does is set the user's is_active flag to False in the database. You can absolutely write your own views to do that too.

restive phoenix
#

function in views

def user_update(request):
    if request.method == "POST":
        disable_form = DisableUserForm(request.POST, instance=request.user)
        if disable_form.is_valid():
            disable_form.save()
            messages.success(request, "User Updated!")
            return redirect('/ims')
    else:
        disable_form = DisableUserForm(instance=request.user)
    context = {
        'disable_form':disable_form,
        "title": "Disable User",
    }
    return render(request, 'IM_sys/disable_user.html', context=context)```
forms.py
```python
class DisableUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['is_active']
#

Thx! Here is my code, this actually works but it deactivated the account I currently logged in instead of the selected user’s account. Is there something wrong here?

tame prism
#

Yes. You passed request.user as the instance to the form, which is the logged in user!

restive phoenix
#

Should I redo the instance or request.user?

tame prism
#

request.user is always the logged in user. You'll need to pass a different user instance to the form, the user you want to deactivate

restive phoenix
#
def manager_list1(request):
    users = User.objects.all() 
    return render (request, "IM_sys/manager_list1.html", {"users":users})
def manager_list2(request):
    results = request.GET['user']
    if request.method == "GET":
        disable_form = DisableUserForm(request.GET, instance=results)
        if disable_form.is_valid():
            disable_form.save()
            messages.success(request, "User Disable!")
            return redirect('/ims')
    else:
        disable_form = DisableUserForm(instance=results)
    return render (request, "IM_sys/manager_list2.html", {"user":results})```
I added this two function into views but seems it is not working...
#

manger_list1.html

<div class="alert alert-success" role="alert">
    <h4 class="alert-heading">User List:
        <form action="{% url 'manager_list2' %}">
        <select name="user">
            <option disabled="true" selected>-- User Names--</option>
            {% for result in users %}
                <option>{{result.username}}</option>
            {% endfor %}
        </select>
        <input type="submit" value="click">
    </h4>
</div>

manager_list2.html

<div class="alert alert-success" role="alert">
    <h4 class="alert-heading">User List:
        <h3>The selected user is: {{user}}</h3>
        <br/>
        <a href="{% url 'manager_list1' %}">Go to Page1</a>
</div>```
#

I did make some mistake in the functions?
for the method of selecting specific user, I was following this video:
https://www.youtube.com/watch?v=0x0pWrm2nKI

#PythonDjango #DropdownSelect #SelectedValue

Django Pass and Get The Selected Value Dropdown select option

In Django, to pass and retrieve the selected value from a dropdown select option, use the request object to access the value sent via a POST or GET request. In the HTML template, create a select element with option tags, and set the name ...

▶ Play video
tame prism
#

request.GET['user'] is going to be the value from the dropdown in the form you submitted. That's not a User instance, it's a string. You can't pass that to the DisableUserForm and expect it to work. You need to first fetch the User instance that corresponds to whatever your form submitted.

Secondly, please do NOT disable a user using a GET request. They should be used for fetching information, and shouldn't change any state on the server. You should be doing this with a POST request from the form instead.

restive phoenix
#

Sorry, I dont really understand wdym "fetch the User instance"

tame prism
#

You want to deactivate a User. You do that by changing the is_active flag on that User. So you need to get that User from the database, change the flag, and save it back

#

At the moment, you're never getting that user from the database. You're reading a string from the query string.

restive phoenix
tame prism
restive phoenix
#

the class

class DisableUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['is_active']
tame prism
#

Oh. No, that doesn't get anything from the database. That just makes a form that matches the fields you specified.

#

If you want to update a user using that form, you need to pass in a User to the instance argument

restive phoenix
#

So I have to get the user by using POST?

tame prism
#

Like you're trying to do: but you're passing in the username as a string, not the User object.

tame prism
restive phoenix
tame prism
#

I don't follow.

#

What do you understand of how HTTP works, and how websites work?

restive phoenix
#

I am a newbie to this topic.. sorry for that

tame prism
#

There are different types of HTTP requests. When you click around websites, clicking on links or typing in URLs, you are sending GET requests to the server. They should be used to fetch and display information in the webpage

#

When you want to change something on the server, like updating your profile or changing your password or submitting a form to do something, they should be what are called POST requests.

#

In your case, I suggest you do the following:

  1. Add method="post" to your form in manager_list1.html
  2. Add {% csrf_token %} inside that form. This is needed for in all POST requests for Django's cross-site request forgery protection, which is important but you don't need to understand right now.
  3. Change GET to POST in the couple of places it's mentioned in manager_list2.html.
  4. Add some code to convert the username string that's currently stored in the results variable into an actual User object. Probably something like user = User.objects.get(username=results), though that has no error handling (what to do if the username doesn't exist etc).
  5. Pass that as the instance argument to the form.
#

It's still not going to actual disable the user, though, because you're never actually rendering the DisableUserForm and giving anybody the chance to uncheck the is_active attribute for the user. The way you're doing this, I see no reason for that DisableUserForm at all. But I'm a bit worried you don't have the basics of Django down at all yet, and I suggest you follow a good complete Django tutorial first to understand how models, views, and forms all work together.

restive phoenix
#

This is what I did yesterday, this delete the current user instead of selected user. What I have to try is to combine this function with the manager_list2 in view.py?

@login_required
def user_update(request):
    if request.method == "POST":
        disable_form = DisableUserForm(request.POST, instance=request.user)
        if disable_form.is_valid():
            disable_form.save()
            messages.success(request, "User Updated!")
            return redirect('/ims')
    else:
        disable_form = DisableUserForm(instance=request.user)
    context = {
        'disable_form':disable_form,
        "title": "Disable User",
    }
    return render(request, 'IM_sys/disable_user.html', context=context)
tame prism
#

At least you're actually using a dedicated template for deactivating the user in that one, in which you're presumably actually rendering the DisableUserForm

#

But honestly, using a ModelForm for that is massively overkill.

#
user = User.objects.get(username=SOMETHING)
user.is_active = False
user.save()```
#

That's all you need. You don't need the DisableUserForm, you just need some way to get the username from a list of users (which you have done above), and then call that code with it.

restive phoenix
#

OMGGG, it works!!! Thank you so much!!!!

tame prism
#

Great! Now make sure you spend some time fully understanding every piece of the code 😊