我试图在我的views.py中使用CreateView泛型类,并且它所引用的模型具有用户属性(来自django的内置User类)作为外键。
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?
答案 0 :(得分:0)
您必须创建User
的实例,然后将此实例附加到UserProfile user
字段。
由于未为UserProfile
定义这些字段(last_name,password1,用户名,电子邮件,password2,first_name)而导致错误
而且BTW django的User
类没有password1
和password2
属性