indianLeo
indianLeo

Reputation: 153

Field 'id' expected a number but got 'User'

I am trying to get the username through POST and filter out the user and save it to the model. Whenever I am trying to migrate I am getting the error "Field 'id' expected a number but got 'User'"

def newrequest(requests):
if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent'):
    if requests.method == 'POST':
        principalamount = requests.POST['principalamount']
        interest = requests.POST['interest']
        emi = requests.POST['emi']
        tenure = requests.POST['tenure'] 
        applicantsalary = requests.POST['applicantsalary']
        applicantname = requests.POST['applicantname']
        applicantcity = requests.POST['applicantcity']
        bankname = requests.POST['bankname']
        accountnumber = requests.POST['accountnumber']
        age = requests.POST['age']
        email = requests.POST['email']

        user = User.objects.get(email__email=email)

        loan = Loan(
            user = user,
            principalamount = principalamount,
            interest = interest,
            emi = emi,
            tenure = tenure,
            applicantsalary = applicantsalary,
            applicantname = applicantname,
            applicantcity = applicantcity,
            bankname = bankname,
            accountnumber = accountnumber,
            age = age,
        )
        loan.save()
    return JsonResponse({"message": "Loan Requested"})
else:
    return HttpResponseForbidden()

This is my Model:

class Loan(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    loanid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    principalamount = models.IntegerField()
    interest = models.IntegerField()
    emi = models.IntegerField()
    tenure = models.IntegerField() 
    applicantsalary = models.IntegerField()
    applicantname = models.CharField(max_length=300)
    applicantcity = models.CharField(max_length=25)
    bankname = models.CharField(max_length=100)
    accountnumber = models.CharField(max_length=25)
    age = models.IntegerField(null=True)

This is the Traceback error is whit the relevant model file above:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, loansystem, sessions
Running migrations:
  Applying loansystem.0007_loan_user...Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'Ankur'

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 85, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
    schema_editor.add_field(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field
    self._remake_table(model, create_field=field)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table
    self.effective_default(create_field)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\schema.py", line 303, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 971, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 823, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2388, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
    raise e.__class__(
ValueError: Field 'id' expected a number but got 'Ankur'.

Here is the Migration file:

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('loansystem', '0014_auto_20201007_2357'),
    ]

    operations = [
        migrations.AlterField(
            model_name='loan',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
    ]

enter image description here

Upvotes: 1

Views: 1748

Answers (3)

BJ_GOST
BJ_GOST

Reputation: 31

check the default value of the user foreign key in your Loan model

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477230

userid is not the id of a user, it is a QuerySet that wraps a collection of userids. It also does not make much sense to do this, since you can immidiately retrieve the user with:

from django.contrib.auth.decorators import login_required

@login_required
def newrequest(requests):
    if requests.user.userrank.userstatus == 'Agent':
        if requests.method == 'POST':
            principalamount = requests.POST['principalamount']
            interest = requests.POST['interest']
            emi = requests.POST['emi']
            tenure = requests.POST['tenure'] 
            applicantsalary = requests.POST['applicantsalary']
            applicantname = requests.POST['applicantname']
            applicantcity = requests.POST['applicantcity']
            bankname = requests.POST['bankname']
            accountnumber = requests.POST['accountnumber']
            age = requests.POST['age']
            email = requests.POST['email']
            user = User.objects.get(email__email=email)

            loan = Loan(
                user =user,
                principalamount = principalamount,
                interest = interest,
                emi = emi,
                tenure = tenure,
                applicantsalary = applicantsalary,
                applicantname = applicantname,
                applicantcity = applicantcity,
                bankname = bankname,
                accountnumber = accountnumber,
                age = age,
            )
            loan.save()
        return JsonResponse({"message": "Loan Requested"})
    else:
        return HttpResponseForbidden()

That being said, you might want to use a ModelForm [Django-doc]. This makes validating and saving the object more convenient.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

Upvotes: 1

Lord Elrond
Lord Elrond

Reputation: 16042

You are using the user keyword, which in this case references a User object. Instead of passing a user object, you are passing a an array of dictionaries, something like this: [{'id': 1}, ...]

To fix this, drop the .values clause:

user = User.objects.get(email__email=email)
loan = Loan(
    user=user,
    ...
)

Note that User.objets.get will throw an error when the email field for the user isn't unique.

Upvotes: 1

Related Questions