django:两种模式形式不保存

时间:2016-01-31 03:33:19

标签: python django django-forms

我跟随instruction使用用户模型和个人资料模型创建表单。我认为输入的数据已成功上传到查看功能,但数据未保存到数据库,因为当我重新加载页面时数据消失了。你有什么想法帮助我吗?谢谢。

models.py

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE)
    pic = models.ImageField(upload_to=user_directory_path,
                            blank=True,
                            default=static('img/jenny.jpg')
    )
    bio = models.CharField(max_length=100, blank=True)
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES,
                              blank=True)
    website = models.URLField(max_length=50, blank=True)
    city = models.CharField(max_length=30, blank=True)
    country = models.CharField(max_length=30, blank=True)

    def __str__(self):
        return self.user.username



@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def ensure_profile_exists(sender, **kwargs):
    if kwargs.get('created', False):
        Profile.objects.get_or_create(user=kwargs.get('instance'))

forms.py

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'last_name', 'first_name']


class ProfileForm(ModelForm):
    def __init__(self, *args, **kwargs):
        # magic
        self.user = kwargs['instance'].user
        user_kwargs = kwargs.copy()
        user_kwargs['instance'] = self.user
        self.uf = UserForm(*args, **user_kwargs)
        # magic end

        super(ProfileForm, self).__init__(*args, **kwargs)

        self.fields.update(self.uf.fields)
        self.initial.update(self.uf.initial)

    def save(self, *args, **kwargs):
        self.uf.save(*args, **kwargs)
        return super(ProfileForm, self).save(*args, **kwargs)

    class Meta:
        model = Profile
        fields = '__all__'

views.py

@method_decorator(login_required, name='dispatch')
class ProfileUpdateView(UpdateView):
    model = Profile
    template_name = 'profiles/update.html'
    form_class = ProfileForm


    def get_object(self, queryset=None):

        if queryset is None:
            queryset = self.get_queryset()

        profile = queryset.get(pk=self.request.user.profile.pk)

        return profile

1 个答案:

答案 0 :(得分:0)

我有同样的问题,我写了一篇关于它的博客文章Extend Django User Model and Generic Class Based View “GCBV”,对不起,我不能在这里写下完整的答案,让你在那里有完整的代码灵魂。