如何解决TypeError:在查询集上工作时,Post在命令行中获得了意外的关键字参数“ body”
我正在使用Django创建博客应用,并且在使用cmd设置查询集时遇到了以下错误,
在CMD中编码:
from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='mratyunjay')
>>> post = Post(title='Another post',... slug='another-post',... body='Post body.',... author=user)
错误:
Traceback (most recent call last):
File "<console>",line 4,in <module>
File "C:\Users\Computer\Desktop\project\my_env\lib\site-packages\django\db\models\base.py",line 501,in __init__
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__,kwarg))
TypeError: Post() got an unexpected keyword argument 'body'
admin.py:-
from django.contrib import admin
# Register your models here.
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ( 'title','slug','author','publish','status')
list_filter = ( 'status','created','author')
search_fields = ( 'title','body' )
prepopulated_fields = {'slug': ('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ( 'status','publish' )
models.py:-
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),('published','Published'),)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,unique_for_date='publish')
author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts')
body = models.TextField
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
class Meta:
ordering = ( '-publish',)
def __str__(self):
return self.title
models.py中的错误:-
User model imported from django.contrib.auth.models pylint(imported-auth-user) [5,1]
我是Django新手,不知道如何解析用户模型,并且在创建查询集时出现了另一个错误。我该如何解决?
解决方法
您在models.py文件中缺少带有正文字段的()。看起来应该像这样。
body = models.TextField()
然后,运行以下命令,
python manage.py makemigrations
python manage.py migration
然后尝试在命令行中编写代码
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。