ValueError:无法为'author'创建表单字段,因为尚未加载其相关模型'settings.AUTH_USER_MODEL'

时间:2017-12-16 16:14:28

标签: python django custom-authentication

我正在尝试使用自定义身份验证模型设置基本博客。我试图让一个简单的形式工作,但不知何故,我无法使其工作。我不确定导致错误的原因。这是一个新鲜的应用程序和我正在研究的新项目。

我试图从文档中引用,但我不确定我做错了什么。我该如何解决这个错误?提前致谢

文档:https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project

类似问题:Cannot create form field for 'created_by' yet, because its related model 'users.User' has not been loaded yet

我当前的代码

models.py

class User(AbstractUser):
  pass

class Post(models.Model):
   author = models.ForeignKey('settings.AUTH_USER_MODEL')
   title = models.CharField(max_length=200)
   text = models.TextField()
   created_date = models.DateTimeField(default=timezone.now)
   published_date = models.DateTimeField(blank=True, null=True)

forms.py:

from blog.models import User

class PostForm(forms.ModelForm):
image = forms.CharField(
    widget=forms.FileInput(attrs={'class': 'form-control'}),required=False)


class Meta():
    model = Post
    fields = ('author','title', 'text','image')
    widgets = {
        'title': forms.TextInput(attrs={'class': 'textinputclass'}),
         }

views.py

from blog.forms import PostForm, CommentForm

class CreatePostView(LoginRequiredMixin,CreateView):
  ...
  form_class = PostForm
  model = Post
  def form_valid(self,form):
    if self.request.POST:
        post = form.save()
        return HttpResponseRedirect('/')

settings.py:

AUTH_USER_MODEL = 'blog.User'

admin.py:

from .models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User,UserAdmin)

1 个答案:

答案 0 :(得分:2)

您应该使用delete,而不是字符串settings.AUTH_USER_MODEL

'settings.AUTH_USER_MODEL'