Django:将新字段添加到模型中后未显示在表单中

时间:2019-03-28 01:03:22

标签: python django forms model

在我的模型中添加新字段后,该字段不会显示在表单中。

我一直在开发这个django应用程序,并用我自己的UserProfile模型和其他字段扩展了已经存在的User模型。最近,我决定向UserProfile模型(profile_type)添加一个额外的字段。我将其添加到模型中,并以其对应的形式包括在内,并进行了makemigrations和migrations。然后,我尝试在视图中向该字段插入一个初始值,并发现它没有通过print()出现在表单中,但是其他所有字段都是。

我的UserProfile模型

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, related_name='userprofile')
    gender = models.CharField(max_length = 10)
    city = models.CharField(max_length = 45)
    country = models.CharField(max_length = 45)
    birthdate = models.DateField(null=True)
    phone_number = models.CharField(max_length = 15)
    profile_type = models.CharField(max_length = 6)


@receiver(post_save, sender=User)
def save_profile(sender, instance, created, **kwargs):
    if created:
        profile = UserProfile(user=instance)
        profile.save()

我的UserProfile表单(UserProfileForm包含注册所必需的字段,其余的则是AdditionalUserProfileForm)

class UserProfileForm(UserCreationForm):

    class Meta:
        model = User    
        fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2')

    def save(self, commit=True):
        user = super(UserProfileForm, self).save(commit=True)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        return user

class AdditionalUserProfileForm(forms.ModelForm):
    profile_type = forms.CharField(max_length=6)

    class Meta:
        model = UserProfile
        fields = ('gender', 'city', 'country', 'birthdate', 'phone_number', 'profile_type')

“我的注册”视图(我想在实例化时将值手动添加到profile_type中

@transaction.atomic
def signup_view(request):
    if request.method == 'POST':
        user_profile_form = UserProfileForm(request.POST)
        initial = {
            'profile_type': 'user'
        }
        additional_user_profile_form = AdditionalUserProfileForm(request.POST, initial=initial)
        valid = user_profile_form.is_valid() * additional_user_profile_form.is_valid()
        if valid:
            user = user_profile_form.save()
            for field in ['gender', 'city', 'country', 'birthdate', 'phone_number']:
                setattr(user.userprofile, field,
                        additional_user_profile_form.cleaned_data.get(field))
            user.userprofile.save()
        return redirect('login')
    else:
        user_profile_form = UserProfileForm()
        additional_user_profile_form = AdditionalUserProfileForm()
        context = {
            'user_profile_form': user_profile_form,
            'additional_user_profile_form': additional_user_profile_form,
        }
        return render(request, 'registration/signup.html', context)

在终端中打印出表单字段并不表示profile_type是其中之一。我在某个线程上看到这是一个错误,但修复程序对我不起作用。关于更改contrib / admin / options.py中的get_fieldsets函数。希望这能给您提示。谢谢!

0 个答案:

没有答案