Justin O'Brien
Justin O'Brien

Reputation: 129

Setting a field on a model not using a form

I have a site that when a user clicks a bootstrap glyphicon link they should be redirected to another page, this page is of the same glyphicon but in a green color to make it seem as if by pressing the link they activated the button. During this trasition I want the field active on my Profile to go from False to True. I have the following code:

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    university = models.CharField(max_length=30, blank=True)

    ROLE = (
        ('CUSTOMER', 'User'),  # (value to be set on model, human readable value)
        ('WORKER', 'Worker'),
    )

    role = models.CharField(max_length = 20, choices = ROLE, default = 'USER')


    active = models.BooleanField(default = False)

views.py

def active(request):
    request.user.profile.active = True;
    return render(request, 'core/customer_active.html', {'user': request.user})

home.html:

<a href="{% url 'active' %}"><span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span></href>

I am not sure why request.user.profile.active = True; does not update the state of the field, what will?

Upvotes: 3

Views: 34

Answers (2)

YellowShark
YellowShark

Reputation: 2269

Is this a permanent change to the "active" property? You need to save the user object, if so. Like this:

def active(request):
    request.user.profile.active = True;
    request.user.save()
    return render(request, 'core/customer_active.html', {'user': request.user})

Edit: might be worth noting that this isn't the smartest way to update a user's profile, by saving this attribute every time they hit this view, but if you're just wondering why the True value isn't persisting, this is the reason why.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

As others have said, you need to save. However, it is the profile you need to save, not the user, since that is a separate model.

profile = request.user.profile
profile.active = True
profile.save()

Upvotes: 2

Related Questions