Django CreateView 自动填充自定义用户

Django CreateView autofill custom user

我想使用 Django 的 GCBV CreateView to autofill the created_by field on my model with the current user. The official docs have a good example here,但我使用的是自定义用户模型并且无法正常工作。

这是我当前的设置:

# models.py
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, 
        on_delete=models.CASCADE,
    )

# views.py
from django.contrib.auth import get_user_model
from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

    def form_valid(self, form):
        form.instance.created_by = self.request.get_user_model()
        return super().form_valid(form)

但是在提交表单时我收到错误:

AttributeError at /posts/new/
'WSGIRequest' object has no attribute 'get_user_model'

如果我不尝试自动包含用户,则表单工作正常,这就是为什么我不认为问题出在我的自定义用户配置上。该代码如下所示:

class PostCreateView(CreateView):
    model = Author
    fields = ['name', 'created_by']

要修复您看到的特定错误,应该可以直接使用 self.request.user,如您链接的示例所示。 (假设自定义用户模型设置正确。)

form.instance.created_by = self.request.user

get_user_model函数一般是这样访问User的class:

from django.contrib.auth import get_user_model
User = get_user_model()

一般代替

from django.contrib.auth.models import User