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

问题描述 投票:1回答:1

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

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

文件: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.朋友

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.朋友:

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.朋友

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.朋友:

AUTH_USER_MODEL = 'blog.User'

admin.朋友:

from .models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User,UserAdmin)
python django custom-authentication
1个回答
2
投票

你应该使用settings.AUTH_USER_MODEL,而不是字符串'settings.AUTH_USER_MODEL'

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
© www.soinside.com 2019 - 2024. All rights reserved.