python - 在django内如何让后台增加的文章自动加上是哪个用户编辑的呢?
问题描述
我写的代码(只贴主要部分):
admin.py
from django.contrib import adminfrom .models import Tag, Category, Articleclass ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change):obj.author = request.userobj.save()admin.site.register(Tag)admin.site.register(Category)admin.site.register(Article)
models.py
from django.db import modelsfrom django.contrib.auth.models import Userclass Tag(models.Model): class Meta:verbose_name = ’标签’verbose_name_plural = verbose_name tag_name = models.CharField(’标签名’, max_length=20) create_time = models.DateTimeField(’创建时间’, auto_now_add=True) def __str__(self):return self.tag_nameclass Category(models.Model): class Meta:verbose_name = ’分类’verbose_name_plural = verbose_name name = models.CharField(’分类名’, max_length=20) def __str__(self):return self.nameclass Article(models.Model): class Meta:verbose_name = ’文章’verbose_name_plural = verbose_nameordering = [’-updated_time’, ’-created_time’] title = models.CharField(’标题’, max_length=60) content = models.TextField(’正文’) category = models.ManyToManyField(Category, verbose_name=’分类’, blank=True) author = models.ForeignKey(User, verbose_name=’作者’, editable=False) tags = models.ForeignKey(Tag, verbose_name='标签', related_name=’tags_article’, blank=True) view_count = models.IntegerField(’浏览次数’, editable=False,default=0) created_time = models.DateTimeField(’添加时间’, auto_now_add=True) updated_time = models.DateTimeField(’修改时间’, auto_now=True) def __str__(self):return self.title
在后台增加文章,抛出错误:
Internal Server Error: /admin/blog/article/add/Traceback (most recent call last): File 'C:Userscxgrefancybloglibsite-packagesdjangodbbackendsutils.py', line 65, in execute return self.cursor.execute(sql, params) File 'C:Userscxgrefancybloglibsite-packagesdjangodbbackendssqlite3base.py', line 328, in execute return Database.Cursor.execute(self, query, params)sqlite3.IntegrityError: NOT NULL constraint failed: blog_article.author_idThe above exception was the direct cause of the following exception:Traceback (most recent call last): File 'C:Userscxgrefancybloglibsite-packagesdjangocorehandlersexception.py', line 41, in inner response = get_response(request) File 'C:Userscxgrefancybloglibsite-packagesdjangocorehandlersbase.py', line 187, in _get_response response = self.process_exception_by_middleware(e, request) File 'C:Userscxgrefancybloglibsite-packagesdjangocorehandlersbase.py', line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangocontribadminoptions.py', line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangoutilsdecorators.py', line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangoviewsdecoratorscache.py', line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangocontribadminsites.py', line 224, in inner return view(request, *args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangocontribadminoptions.py', line 1508, in add_view return self.changeform_view(request, None, form_url, extra_context) File 'C:Userscxgrefancybloglibsite-packagesdjangoutilsdecorators.py', line 67, in _wrapper return bound_func(*args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangoutilsdecorators.py', line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangoutilsdecorators.py', line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File 'C:Userscxgrefancybloglibsite-packagesdjangocontribadminoptions.py', line 1408, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File 'C:Userscxgrefancybloglibsite-packagesdjangocontribadminoptions.py', line 1448, in _changeform_view self.save_model(request, new_object, form, not add) File 'C:Userscxgrefancybloglibsite-packagesdjangocontribadminoptions.py', line 979, in save_model obj.save() File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelsbase.py', line 806, in save force_update=force_update, update_fields=update_fields) File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelsbase.py', line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelsbase.py', line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelsbase.py', line 961, in _do_insert using=using, raw=raw) File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelsmanager.py', line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelsquery.py', line 1063, in _insert return query.get_compiler(using=using).execute_sql(return_id) File 'C:Userscxgrefancybloglibsite-packagesdjangodbmodelssqlcompiler.py', line 1099, in execute_sql cursor.execute(sql, params) File 'C:Userscxgrefancybloglibsite-packagesdjangodbbackendsutils.py', line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File 'C:Userscxgrefancybloglibsite-packagesdjangodbbackendsutils.py', line 65, in execute return self.cursor.execute(sql, params) File 'C:Userscxgrefancybloglibsite-packagesdjangodbutils.py', line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File 'C:Userscxgrefancybloglibsite-packagesdjangoutilssix.py', line 685, in reraise raise value.with_traceback(tb) File 'C:Userscxgrefancybloglibsite-packagesdjangodbbackendsutils.py', line 65, in execute return self.cursor.execute(sql, params) File 'C:Userscxgrefancybloglibsite-packagesdjangodbbackendssqlite3base.py', line 328, in execute return Database.Cursor.execute(self, query, params)django.db.utils.IntegrityError: NOT NULL constraint failed: blog_article.author_id
我该怎么做呢?
问题解答
回答1:admin.py中定义了ArticleAdmin 但并没有绑定注册。 所以ArticleAdmin没有生效。 需要改成如下
from django.contrib import adminfrom .models import Tag, Category, Articleclass ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change):obj.author = request.userobj.save()admin.site.register(Tag)admin.site.register(Category)admin.site.register(Article, ArticleAdmin)
相关文章:
1. javascript - 如何在windows下搭建react开发环境上,实现网站的react版本2. html5 - 移动端通过拖拽实现两个元素的位置互换3. javascript - 读取页面源码,页面中所有的换行都被当成<br/>读取出来 了,,求解应该怎么让它被正确的解析4. javascript - 呈现引擎是什么?5. javascript - 一个字符串转换成数字,例子就是a="2,322.222",b=’1,211.21’,如何在angualr中执行相减6. windows - python pymysql 返回值是int类型7. mysql sql where id in(25,12,87) 结果集如何用按照 25 12 87排序?8. PHP类属性声明?9. 利用百度地图API定位及附件商家信息服务10. javascript - easyui textbox绑定onchange事件不能获取最新的文本框的值