我有这个自定义用户模型'es_user'
models.py
class 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.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
return super(CreateEventView, self).form_valid(form)
提交表单时出现此错误
Cannot assign "<SimpleLazyObject: <User: randy>>": "es_event.ev_admin" must be a "es_user" instance.
我已经检查了Django文档和其他堆栈溢出帖子,但是在所有这些内容中,外键都引用了Django的内置用户模型
答案 0 :(得分:1)
因此,只需分配es_user,而不是auth用户。
form.instance.ev_admin = self.request.user.es_user
答案 1 :(得分:0)
您可以改为获取es_user
:
form.instance.ev_admin = es_user.objects.get(user=self.request.user)
答案 2 :(得分:0)
当我对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)