如何在默认情况下将Django布尔值设置为True,它是否为false?

时间:2013-06-23 02:46:19

标签: django boolean django-views django-models

我有一个用户可以注册的django视图。对于从这一点向前注册的任何用户,我想将布尔值设置为True。

 class Person(models.Model):
      user = models.OneToOneField(User, primary_key=True)
      facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
      twitter_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
      suggested_person = models.BooleanField(default=False)
      userPic = models.CharField(max_length=128, blank=True)
      phoneNum = models.CharField(max_length=128, blank=True)

注册Django视图:

 @csrf_exempt
 def signup(request):

     if request.method == 'POST':
         # Parse the JSON
         data = json.loads(request.raw_post_data)
         # Check if the user already exists
         if User.objects.filter(username = data['username']).exists():
             return HttpResponse("Username already exists")

         # If not then create new user with the supplied info
         else:
             newUser = User()
             newUser.username = data['username']
             newUser.email = data['email']
             newUser.set_password(data['password'])
             newUser.first_name = data['firstName']
             newUser.last_name = data['lastName']
             newUser.save()

             newPerson = Person(user = newUser, phoneNum = data['phoneNum'], userPic = data['userPic'], userCover = data['userCover'])
             if 'token' in data:
                 if Person.objects.filter(token=data['token']).exists():
                     oldToken = Person.objects.get(token=data['token'])
                     oldToken.token = None
                     oldToken.save()
                     newPerson.token = data['token']
                     newPerson.save()
                 else:
                     newPerson.token = data['token']
                     newPerson.save()

     #perhaps like this? newPerson.suggested_person =True
             newPerson.save()
             newUser.relationships.add(newUser)

             return HttpResponse(str(newUser.id))

     # If not POST  
     else:
         return HttpResponse("Signup here People")

如何让从此点注册的用户转发为“recommended_person”?

1 个答案:

答案 0 :(得分:2)

如果您不能或不想更改模型的默认定义,您可以在创建Person实例时传入所需的值:

newPerson = Person(user = newUser, phoneNum = data['phoneNum'], userPic = data['userPic'], userCover = data['userCover'], suggested_person=True)

或者您可以在保存之前设置属性:

newPerson.suggested_person = True