为什么这行得通?? Class元,模型=用户

Why does this work?? Class Meta, model = User

有人可以解释一下吗??我正在尝试我的第一个 post-教程项目。

我制作了一个名为 Profile 的模型,其中包含 4 个属性(given_name、姓氏、简历、图像)。我制作了一个名为 ProfileForm 的表单,它继承自 UserCreationForm,并且我已将模型的 4 个属性作为表单属性添加到表单中。

我的问题是:

为什么只能这样

class Meta:
   model = User

这是我的 models.py 文件

class Profile(models.Model):
    given_name = models.CharField(max_length=255)
    surname = models.CharField(max_length=255)
    bio = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='uploads/', blank=True, null=True)

    def __str__(self):
        return self.given_name

    class Meta:
        ordering = ['given_name']

这是我的 forms.py 文件

class ProfileForm(UserCreationForm):
    firstName = forms.CharField(max_length=255)
    lastName = forms.CharField(max_length=255)
    bio = forms.CharField(widget=forms.Textarea)
    image = forms.ImageField()

    class Meta:
        model = User
        fields = ['firstName', 'lastName', 'username', 'password1', 'password2', 'bio', 'image']

这是我的 views.py 文件

def sign_up_view(request):
    if request.method == "POST": 

        form = ProfileForm(request.POST, request.FILES) 

        if form.is_valid(): 
            user = form.save()
            login(request, user)

            profile = Profile.objects.create(
                given_name=form.cleaned_data['firstName'], 
                surname = form.cleaned_data['lastName'],
                bio = form.cleaned_data['bio'],
                image = form.cleaned_data['image'])

            

            return redirect('home')

    else:
        form = ProfileForm()   

    return render(request, 'core/sign_up.html', {"form": form})

这是我的个人资料管理页面。

这是我的用户管理页面

注意:我能够实现我想要的结果,但我无法理解它的工作原理。 **此外,如果我想 link 用户的配置文件模型,这样,如果用户在管理员中被删除,那么相应的配置文件也会被删除??

它仅适用于 model = User,因为您的字段,如 username 等,是 User 模型的字段,而不是 Profile 模型的字段。

您可以做的是用两种形式处理视图。因此,我们为 Profile 模型制作一个表格,并使用 UserCreationFormUser.

另外Profile需要link用户模型,这样就很清楚Profile属于什么用户。因此我们添加了一个 ForeignKey with:

from django.conf import settings

class Profile(models.Model):
    # ⋮
    user = <strong>models.OneToOneField(</strong>
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        editable=False
    <strong>)</strong>

    # ⋮

然后我们可以定义一个 Profile 形式:

class ProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = <strong>'__all__'</strong>

然后我们可以使用两种形式,视图如下所示:

from django.contrib.auth.forms import UserCreationForm

def sign_up_view(request):
    if request.method == 'POST':
        user_form = UserCreationForm(request.POST, request.FILES)
        profile_form = ProfileForm(request.POST, request.FILES, prefix='profile')

        if user_form.is_valid() and profile_form.is_valid(): 
            user = form.save()
            profile_form<strong>.instance.user = user</strong>
            profile_form.save()
            login(request, user)
            return redirect('home')

    else:
        user_form = UserCreationForm()
        profile_form = ProfileForm(prefix='profile')
    context = {'user_form': user_form, 'profile_form': profile_form}
    return render(request, 'core/sign_up.html', context)

并在模板中渲染它:

<form action="{% url '<em>name-of-the-signup-view</em>' %}" method="post" <strong>enctype="multipart/form-data"</strong>>
    {% csrf_token %}
    {{ <strong>user_form</strong> }}
    {{ <strong>profile_form</strong> }}
</form>

因此,我们在相同的 HTML 表单中使用两个 Django 表单,并在 ProfileForm 前加上 profile 作为输入字段的前缀。