我有这个自定义用户模型“es_user”models.pyclass es_user(models.Model):user = models.OneToOneField(User, on_delete=models.CASCADE)class es_event(models.Model): ev_name = models.CharField(max_length=100) ev_venue = models.CharField(max_length=100) ev_admin = models.ForeignKey('es_user',related_name='events',on_delete=None)最终,我将向 es_user 添加更多字段,这就是我使用自定义用户模型的原因。所以我不能满足于 django 的内置用户模型。views.pyclass CreateEventView(LoginRequiredMixin,CreateView): model = es_event fields = ['ev_name','ev_venue','ev_date','ev_description'] def form_valid(self, form): form.instance.ev_admin = self.request.user return super(CreateEventView, self).form_valid(form)当我提交表单时出现此错误Cannot assign "<SimpleLazyObject: <User: randy>>": "es_event.ev_admin" must be a "es_user" instance.我已经检查了 Django 文档和其他堆栈溢出帖子,但在所有这些帖子中,外键都引用了 Django 的内置用户模型
3 回答
明月笑刀无情
TA贡献1828条经验 获得超4个赞
所以只分配 es_user,而不是 auth 用户。
form.instance.ev_admin = self.request.user.es_user
千巷猫影
TA贡献1829条经验 获得超7个赞
当我对 views.py 和 models.py 进行一些更改时,一切正常
views.py
class CreateEventView(LoginRequiredMixin,CreateView):
model = es_event
fields = ['ev_name','ev_venue','ev_date','ev_description']
def form_valid(self, form):
form.instance.ev_admin = self.request.user.es_user
models.py
class es_user(models.Model):
user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE)
FFIVE
TA贡献1797条经验 获得超6个赞
你可以es_user
取而代之:
form.instance.ev_admin = es_user.objects.get(user=self.request.user)
添加回答
举报
0/150
提交
取消