Django:在具有外键属性的模型中使用 CreateView

Django: Using CreateView in a model with a foreignkey attribute

我正在尝试在我的 views.py 中使用 CreateView generic-class 并且它引用的模型具有用户属性(来自内置用户 class django) 作为外键。

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.urls import reverse

class UserProfile(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    description = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=100,default='')
    website = models.URLField(default='')
    phone = models.IntegerField(default=0)

    def get_absolute_url(self):
        return reverse('profile', kwargs={'pk': self.pk})

views.py

from accounts.models import UserProfile
from django.views.generic.edit import CreateView

class RegisterUserView(CreateView):
    model =  UserProfile
    fields=['username','first_name','last_name','email','password1','password2']

urls.py

path('register/',RegisterUserView.as_view() , name='register')

给出错误:

FieldError at /accounts/register/

Unknown field(s) (last_name, password1, username, email, password2, first_name) specified for UserProfile

Request Method:     GET
Request URL:    http://127.0.0.1:8000/accounts/register/
Django Version:     2.0.6
Exception Type:     FieldError
Exception Value:    

Unknown field(s) (last_name, password1, username, email, password2, first_name) specified for UserProfile

Exception Location:     /home/gaspar/anaconda3/lib/python3.6/site-packages/django/forms/models.py in __new__, line 266
Python Executable:  /home/gaspar/anaconda3/bin/python3
Python Version:     3.6.5
Python Path:    

我的问题是:CreateView 可以从用户属性中获取数据并创建一个 Modelform,还是我必须创建一个自定义 ModelForm?

您必须创建 User 的实例,然后将此实例附加到 UserProfile user 字段。

错误是由于这些字段(last_name、密码 1、用户名、电子邮件、密码 2、first_name)没有为 UserProfile

定义

顺便说一句,django 的 User class 没有 password1password2 属性