我正在Django上创建CRUD,我有用户表和体验表,每个用户可以有多个体验,所以我想将用户ID分配给新体验。当我尝试这样做时,出现错误“ Experience.id_auth_user”必须是“ AuthUser”实例。”
Models.py
class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=150)
email = models.CharField(unique=True, max_length=254)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
perfil_photo = models.CharField(max_length=150, blank=True, null=True)
cel_number = models.CharField(max_length=150, blank=True, null=True)
date_of_birth = models.DateTimeField(blank=True, null=True)
location = models.CharField(max_length=150, blank=True, null=True)
gender = models.CharField(max_length=150, blank=True, null=True)
class Meta:
managed = False
db_table = 'auth_user'
class Experience(models.Model):
experience_name = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
minimum_age = models.IntegerField(blank=True, null=True)
duration = models.IntegerField(blank=True, null=True)
price = models.FloatField(blank=True, null=True)
id_auth_user = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='id_auth_user', blank=True, null=True)
class Meta:
managed = False
db_table = 'experience'
views.py
class ExperienceCreate(CreateView):
model = Experience
fields = ['experience_name','description','duration','price']
def form_valid(self, form):
# form.instance.id_auth_user = Experience.objects(id_auth_user=self.request.user.id)
#instance_experience = Experience.object.id(id_auth_user=self.request.user.id)
#form.instance.id_auth_user = self.request.user
self.object = form.save(commit=False)
self.object.id_auth_user = self.request.user.id
self.object.save()
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('experience')
有什么建议吗?