Answer the question
In order to leave comments, you need to log in
How to autocomplete ForeignKey field in admin?
The following models are available:
class Seller(models.Model):
user_seller = models.ForeignKey(User, blank=True, null=True)
def __str__(self):
return self.user_seller.get_username()
class Item(models.Model):
user = models.ForeignKey(Seller, blank=True, null=True)
# Тут другие поля
def __str__(self):
return self.item_name
def save_model(self, request, obj, form, change):
if form.is_valid():
obj.user = Seller.objects.filter(user_seller = request.user)
obj.save()
Answer the question
In order to leave comments, you need to log in
You need to write
filter() returns not a single object, but a collection of objects - QuerySet . The call to first() returns the first object in the collection, or None if it is empty.
I would write like this:
from django.contrib.auth.models import User
***
def save_model(self, request, obj, form, change):
if form.is_valid():
obj.user = request.user
obj.save()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question