【问题标题】:Django: Using CreateView in a model with a foreignkey attributeDjango:在具有外键属性的模型中使用 CreateView
【发布时间】:2018-12-02 07:18:03
【问题描述】:

我正在尝试在我的views.py 中使用CreateView generic-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?

【问题讨论】:

标签: django django-class-based-views


【解决方案1】:

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

错误是由于这些字段(last_name、password1、username、email、password2、first_name)未为 UserProfile 定义

BTW django 的 User 类没有 password1password2 属性

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多