Reputation: 291
I am trying to store the username of the user currently logged in when they submit information on a form on a django website.
This is what my models.py file looks like so far:
from django.db import models
from django.contrib.auth.models import User
class Transfer(models.Model):
id = models.AutoField(primary_key=True)
username = User._meta.get_field('username')
amount = models.DecimalField(max_digits=10, decimal_places=2)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
however this doesn't seem to work. The migrations etc work fine and the server runs, but when I submit information on the form I get the following error:
Exception Type: IntegrityError
Exception Value: UNIQUE constraint failed: transfer_transfer.username
Any advice on how I could get the username to save would be very helpful.
Thanks in advance
Upvotes: 1
Views: 266
Reputation: 599490
That declaration doesn't make any sense in a model definition. It might "work", in the sense that you get a field with the same properties as User.username, but it isn't doing anything useful; you could just as well define it directly as models.CharField
.
Instead you need to define a ForeignKey from Transfer to User, and call it user
; there is plenty of documentation on how to do this, and also plenty of questions here on how to fill in the user field automatically on form submission.
Upvotes: 1