user3078714
user3078714

Reputation: 1

unresolved reference - django

In new in django and python and don't understand this problem.

I have a model:

class User(models.Model):
    nick = models.CharField(max_length=50)
    age = models.IntegerField() 

and i'm trying to check if the is already a user with the same name entered:

def addUser(request):

    nick1 = request.GET['nick']
    age1 = request.GET['age']

    newUser = User()

    newUser.nick = nick1
    newUser.age = age1
    if User.objects.filter(nick=newUser.nick).count()>0

    newUser.save()

I cannot continue the if statement because it is telling me there is a

unresolved reference 'newUser'

What am I doing wrong here?

Upvotes: 0

Views: 1708

Answers (2)

leonardo
leonardo

Reputation: 1

You have to do:

  def adduser(request):
    nick1 = request.GET['nick']
    age1 = request.GET['age']

    if User.objects.filter(nick=nick1)>0:
      # retur response to user exist
    else:
      User.objects.create(nick=nick1,age=age1)
      # return response user created

Remember to use the correct indentation with python and always put : after every if, orfor` statements.

Upvotes: 0

Foon
Foon

Reputation: 6468

I'd suggest cleaning up your formatting. Assuming your formatting is correct in code and just not correctly transposed to stack overflow, that looks like it should work.

Note that a better way might be:

newUser,created = User.objects.get_or_create(nick=nick1)
if created: #note the colon at the end and the next lines are indented
   newUser.age = age
   newUser.save()
   # e.g. return response indiciating user was created
else:
   # e.g. return a response indiciating that nick already taken

This assumes that there is exactly 1 user for a given nick (will throw an exception if this is not true, which may or may not be what you want). Also note that if your experience is similar to mine, as you improve your understanding of what I'm going to call the Tao of Django, you'll find better ways to do a lot of stuff with templates so even the above is excessive code to write.

Upvotes: 3

Related Questions