When I try to save the info inputted into the form, I get the ValueError
:
Cannot assign "<class 'auctions.models.User'>": "Listing.user" must be a "User" instance.
I think that this may be because the model field Listing.user
is a foreign key between the Listing
model and the User
model.
Even when I change Listing.user = User
to Listing.user = User()
(includes brackets), it returns the ValueError
:
save() prohibited to prevent data loss due to unsaved related object 'user'.
So how do I add who the current user is to the model field Listing.user
?
models.py:
class User(AbstractUser):
pass
class Listing(models.Model):
...
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
views.py:
def save_new(request):
if request.method == 'POST':
form = NewListing(request.POST)
if form.is_valid():
obj = Listing()
...
obj.user = User # this returned the first ValueError
# obj.user = User() - this returned the second ValueError
obj.save()
return HttpResponseRedirect('/')
CodePudding user response:
can you try this
obj.user = User.objects.get(pk=request.user.id)