1

I'm trying to override the save() method in the admin so when my publisher-users are creating their customer-users, the publisher field is automatically assigned a value of current user.

ValueError: Cannot assign "User: foo": "SimpleSubscriber.publisher" must be a "Publisher" instance.

I used this tutorial to get started: here.

def save_model(self, request, obj, form, change):
    if not change:
        obj.publisher = request.user
    obj.save()

this is the save method override. The only users who can access the admin are publishers, and both the Publisher and SimpleSubscriber models are user models:

class Publisher(User):
    def __unicode__(self):
        return self.get_full_name()

class SimpleSubscriber(User):
    publisher = models.ForeignKey(Publisher)
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=100)
    state = USStateField()
    zipcode = models.CharField(max_length=9)
    phone = models.CharField(max_length=10)
    date_created = models.DateField(null=True)
    sub_type = models.ForeignKey(Product)
    sub_startdate = models.DateField()
    def __unicode__(self):
        return self.last_name

What can I replace request.user with in order to assign each new SimpleSubscriber to the current publisher user?

4

1 回答 1

1

您必须替换request.userPublisher.

一种方法是:

Publisher.objects.get(**{Publisher._meta.get_ancestor_link(User).name: request.user})

当然,它会在您每次调用它时进行查找,因此您可能希望将您的应用程序设计为对每个请求执行此操作。

另一种方法是(稍微)滥用 django 模型系统——其中一个模型从另一个模型继承,相应的父模型实例和子模型实例具有相同的id(默认情况下);

Publisher.objects.get(id = request.user.id)
于 2012-07-19T21:57:04.520 回答