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.
我正在尝试覆盖admin中的save()方法,因此当我的发布者用户创建其客户用户时,将自动为发布者字段分配当前用户的值。
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:
这是保存方法覆盖。唯一可以访问管理员的用户是发布者,Publisher和SimpleSubscriber模型都是用户模型:
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?
有什么可以替换request.user以便将每个新的SimpleSubscriber分配给当前的发布者用户?
1 个解决方案
#1
1
You must replace request.user
with an instance of Publisher
.
您必须将request.user替换为Publisher实例。
One way to do that would be:
一种方法是:
Publisher.objects.get(**{Publisher._meta.get_ancestor_link(User).name: request.user})
Of course, that will do a lookup every time you invoke it, so you might like to design your application to do this on every request.
当然,每次调用它时都会进行查找,因此您可能希望设计应用程序以在每次请求时执行此操作。
Another way to do this is to (slightly) abuse the django model system - where one model inherits from another, the corresponding parent and child model instances have the same id
(by default);
另一种方法是(略微)滥用django模型系统 - 其中一个模型继承自另一个模型,相应的父模型实例和子模型实例具有相同的id(默认情况下);
Publisher.objects.get(id = request.user.id)
#1
1
You must replace request.user
with an instance of Publisher
.
您必须将request.user替换为Publisher实例。
One way to do that would be:
一种方法是:
Publisher.objects.get(**{Publisher._meta.get_ancestor_link(User).name: request.user})
Of course, that will do a lookup every time you invoke it, so you might like to design your application to do this on every request.
当然,每次调用它时都会进行查找,因此您可能希望设计应用程序以在每次请求时执行此操作。
Another way to do this is to (slightly) abuse the django model system - where one model inherits from another, the corresponding parent and child model instances have the same id
(by default);
另一种方法是(略微)滥用django模型系统 - 其中一个模型继承自另一个模型,相应的父模型实例和子模型实例具有相同的id(默认情况下);
Publisher.objects.get(id = request.user.id)