如何为与基础User模型有OneToOne连接的模型创建Django表单?

disho6za  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(95)

详细信息在代码中,它本身就说明了这一点。我有一个配置文件模型,其中的字段不在User中,我需要制作一个表单来填充User和Profile中的字段:

class Profile(models.Model):
    user = models.OneToOneField(
        to=User,
        on_delete=models.CASCADE
        )
    rating = models.IntegerField(default=0, blank=False)
    avatar = models.ImageField()
    
    def __str__(self):
        return self.user.string()
    
    def absolute_url(self):
        return f"/post/{self.pk}/"
    
    class Meta:
        db_table = 'profile'
        ordering = ['-user']

class SignUpForm(UserCreationForm):
    username = UsernameField(
        max_length=256,
        label=_('RegisterUsername'),
        widget=forms.TextInput(
            attrs= {
                'class': "form-control"
            }
        ),
    )
    email = forms.CharField(
        max_length=320,
        label=_('RegisterEmail'),
        widget=forms.EmailInput(
            attrs= {
                'class': "form-control"
            }
        ),
    )
    nickname = forms.CharField(
        max_length=256,
        label=_('RegisterUsername'),
        widget=forms.TextInput(
            attrs= {
                'class': "form-control"
            }
        ),
    )
    password1 = forms.CharField(
        max_length=256,
        label=_('RegisterPassword1'),
        widget=forms.PasswordInput(
            attrs= {
                'class': "form-control"
            }
        ),
    )
    password2 = forms.CharField(
        max_length=256,
        label=_('RegisterPassword2'),
        widget=forms.PasswordInput(
            attrs= {
                'class': "form-control"
            }
        ),
    )
    avatar = forms.ImageField(
        label=_('UploadAvatar'),
        widget=forms.FileInput(
            attrs= {
                'class': "btn btn-outline"
            }
        ),
    )
    
    class Meta:
        model = Profile
        fields = [
            'username', 
            'email'
            'nickname'
            'password1', 
            'password2', 
            'avatar', 
        ]

django.core.exceptions.FieldError:为配置文件指定的未知字段(emailnicknamepassword1)
我以为会有效果...

jm2pwxwz

jm2pwxwz1#

在您的views.py

if request.method == "POST":
        
    raw_nickname = request.POST['nickname']
    raw_email = request.POST['email']
    raw_password = request.POST['password']
    raw_first_name = request.POST['first_name']
    raw_last_name = request.POST['last_name']
    raw_avatar = request.POST['avatar']

    user = User.objects.create(
        username=raw_nickname,
        email=raw_email,
        password=raw_password,
        first_name=raw_first_name,
        last_name=raw_last_name
    )

    Profile.objects.create(
        user=user,
        rating=raw_rating,
        avatar=raw_avatar,
    )

相关问题