tangjikededela
tangjikededela

Reputation: 41

How should I read specific data for the specific user from database by python django

For example, in my database, I have a table called BlackList which looks like this: enter image description here

The models of the table is:

class BlackList(models.Model):
    name = models.CharField(max_length=1000, null=True, blank=True)
    flag1 = models.BooleanField(default=False)
    flag2 = models.BooleanField(default=False)
   

What I want to do is something like this:

if request.method == "POST":
    username = request.POST.get('username')  # Get username input first
    password = request.POST.get('password')
    user = authenticate(request, username=username, password=password)
    # BLname = Read the username from the table
    # BLflag1 = read the Flag1 for the user
    # BLflag2 = read the Flag2 for the user
    if BLflag1 == True and BLflag2 == True:  
        something will happen 
    elif BLflag1 == True and BLflag2 == False:  
        something will happen
    else:
        # set the Flag1 and Flag2 of this user to True. 

So, my questions are

  1. How to read the specific data for a specific user, for example, if the User 'aaa' try to log in, the application will read Flag1 for aaa is True and Flag2 for aaa is True.
  2. How to set the Flag for a specific user, for example, if user 'bbb' try to log in, the application will set Flag1 and Flag2 into True in the end.

Upvotes: 0

Views: 199

Answers (1)

Jordan Mora
Jordan Mora

Reputation: 949

You should first check if the user is authenticated.

user = authenticate(request, username=username, password=password)
if user is not None:
    BLname = user.username
    BLflag1 = user.Flag1
    BLflag2 = user.Flag2
    if BLflag1 and BLflag2:  # since the values are boolean, you don't need to compare them  
        # something will happen 
    elif BLflag1 and not BLflag2:  
        # something will happen
    else:
        user.Flag1 = True
        user.Flag2 = True
        user.save()
else:
    # do something for unauthenticated users

Upvotes: 1

Related Questions