Django CreateView自动填充自定义用户

时间:2018-02-08 18:20:23

标签: python django django-custom-user

我想使用Django的GCBV CreateView在当前用户的模型上自动填充created_by字段。官方文档有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']

1 个答案:

答案 0 :(得分:2)

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

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

get_user_model函数通常用于访问User类:

from django.contrib.auth.models import User

一般代替

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">