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('/')
你能试试这个吗
obj.user = User.objects.get(pk=request.user.id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.