为什么我在ModelForm中的实例是以NoneType形式出现的?

时间:2018-02-10 07:36:12

标签: django django-models django-forms django-views

我试图在forms.py ModelForm中获取Profile对象。

print(type(self.instance))将按预期返回<class 'user_profile.models.Profile'>,但print(self.instance)将返回错误:AttributeError: 'NoneType' object has no attribute 'username'

首先是表格:

class PublicToggleForm(ModelForm):

    class Meta:
        model = Profile
        fields = [
            "public",
        ]

    def clean_public(self):
        public_toggle = self.cleaned_data.get("public")
        if public_toggle is True:
            print(type(self.instance))
            print(self.instance)  
        return public_toggle  

以下是模型:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True, related_name='is_profile_to')  
    def __str__(self):
         return self.user.username  

AUTH_USER_MODEL

class User(AbstractUser):

    def __str__(self):
        return self.username

我自己并没有真正设置username字段。我使用了django-allauth,我认为他们有一个username字段。

返回Profile对象作为其用户名的字符串表示,之前没有给我带来任何问题。那么它与我的表格间接地与视图联系的方式有关吗?
我有一个FormView,以及一个插入表单的DetailView:

这是FormView的范围:

class PublicToggleFormView(AjaxFormMixin, FormView):
    form_class = PublicToggleForm
    success_url = '/form-success/'
    template_name = 'user_profile/profile_detail.html'  

还有DetailView:

from .forms import PublicToggleForm  

class ProfileDetailView(DetailView):
    template_name = 'user_profile/profile_detail.html'  

    def get_context_data(self, **kwargs):
        context = super(ProfileDetailView, self).get_context_data(**kwargs)
        profile = Profile.objects.get(
            user__username=self.request.user)
        context['public_toggle_form'] = PublicToggleForm(instance=profile)
        return context  

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,当您致电PublicToggleFormView时,您不会将当前用户的个人资料实例传递给表单。您可以覆盖get_form_kwargs方法来执行此操作:

class PublicToggleFormView(AjaxFormMixin, FormView):
    form_class = PublicToggleForm
    success_url = '/form-success/'
    template_name = 'user_profile/profile_detail.html'  

    def get_form_kwargs(self):
        kwargs = super(PublicToggleFormView, self).get_form_kwargs()
        profile = Profile.objects.get(user=self.request.user)
        kwargs.update({'instance': profile})
        return kwargs