Django save()方法未保存到数据库

时间:2019-06-23 16:01:36

标签: django python-3.x django-models

我在做什么错了?

我有两个表UserEntrepreneur。对象未保存在Entrepreneur表中。我什至用过外壳!

我已删除数据库和迁移文件,并且错误保持不变。

我知道有人问过类似的问题,但我发现没有一个适合我的情况。

我的模型:

class EntrepreneurProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile = models.CharField(max_length=100, blank=True, null=True)
    location = CountryField(blank=True, null=True)
    email_notif_on = models.BooleanField(default=False)
    photo = models.ImageField(upload_to='photo/%Y/%m/%d', blank=True, null=True)
    skills = TaggableManager(blank=True)
    date_joined = models.DateField(auto_now_add=True)
    accomplishnment = models.ForeignKey(Accomplishment, on_delete=models.CASCADE, null=True, blank=True)
    portfolio = models.ManyToManyField(Portfolio, blank=True)
    date_of_birth = models.DateField(blank=True, null=True)
    url = models.SlugField(unique=True)    

    def __str__(self):
        return f'{self.user}'

    def save(self, *args, **kwargs):
        if self.url:
            self.url = slugify(f'{self.user.first_name} {self.user.last_name} {str(uuid.uuid4()[:7])}')

我的观看次数:

def signup(request):
    if request.method == 'POST':    
        user_form = UserCreateForm(request.POST)

        if user_form.is_valid():
            user = user_form.save(commit=False)
            user.set_password(user.password)
            user.save()

            entrep = EntrepreneurProfile.objects.create(user=user)
            entrep.save()

            print(entrep.id)
            return redirect('users:login')
    else:
        user_form = UserCreateForm()
        data = {'user_form': user_form}
        return render(request, 'users/signup.html', data)

1 个答案:

答案 0 :(得分:4)

似乎您忘记了在super().save(*args, **kwargs)方法中调用save,因为 https://docs.djangoproject.com/en/2.2/topics/db/models/#overriding-predefined-model-methods