F
F
fox15102015-02-09 15:48:14
Django
fox1510, 2015-02-09 15:48:14

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

In the Django admin, you need to make sure that when you add an Item, user is automatically set based on the user. Those. the mechanism is as follows: admin (superuser) in the admin panel adds a Seller, after which this Seller can add an Item, and the user field for each Item should be set automatically based on the Seller's data, which adds the Item.
Tried to do like this:
def save_model(self, request, obj, form, change):
      if form.is_valid():
        obj.user = Seller.objects.filter(user_seller = request.user)
        obj.save()

To which Django told me that "Item.user" must be a "Seller" instance. And to tell you the truth, I don't really understand why this error occurs.
PS I'm just starting to learn Django, so don't kick too hard for stupid questions.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly Scherbakov, 2015-02-09
@fox1510

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.

S
Sergey Che, 2020-03-18
@srgtmn

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 question

Ask a Question

731 491 924 answers to any question