是django的新手,我创建了一个模型和一个信号,在更改字段时,它应该触发该信号并使用user_id在另一个模型中创建新记录,但是它给了我这个错误...当我将状态更改为已批准信号应该在他的ApprovedArticle对象中创建一个新对象,但显示错误,我不知道我做错了什么
Model.py
from django.db import models
from article.models import Article
from adminactivities.models import User, ApprovedArticleStatus
from django.utils import timezone
DEFAULT_STATUS = 2
class ApprovedArticle(models.Model):
user = models.ForeignKey(User, on_delete=models.SET('Unknown'))
article = models.ForeignKey(Article, on_delete=models.CASCADE)
link = models.CharField(max_length=150)
views = models.CharField(max_length=150, default=0)
link_views = models.CharField(max_length=150, default='NIL')
approved_status = models.ForeignKey(ApprovedArticleStatus, on_delete=models.SET('Uncategorized'),
default=DEFAULT_STATUS)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
added_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.article.title
def __init__(self, *args, **kwargs):
super(ApprovedArticle, self).__init__(*args, *kwargs)
self.original_views = self.views
DEFAULT_STATUS = 1
class Article( models.Model ):
title = models.CharField( max_length = 250 )
category = models.ForeignKey( ArticleCategory, on_delete = models.SET( "Uncategorized" ) )
status = models.ForeignKey( ArticleStatus, on_delete = models.SET( "Pending" ), default = DEFAULT_STATUS )
user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET( "Unknown" ) )
document = models.FileField( upload_to = 'documents/', null = False )
cover_pic = models.ImageField( default = 'cover.jpg', upload_to = 'cover_pics/' )
date_added = models.DateTimeField( default = timezone.now )
date_updated = models.DateTimeField(auto_now = True)
def __str__( self ):
return self.title
def save( self, **kwargs ):
super().save()
img = Image.open( self.cover_pic.path )
if img.height > 768 or img.width > 1280:
output_size = (1280, 768)
img.thumbnail( output_size )
img.save( self.cover_pic.path )
Signal.py
@receiver(post_save, sender = Article)
def add_approved_article(sender, instance, **kwargs):
if kwargs['created']:
print('Article Created... Perform NO action')
else:
if str(instance.status) == "Approved":
if ApprovedArticle.objects.filter(article_id = instance.pk):
print("Already Exist")
else:
approved = ApprovedArticle.objects.create(user = instance.user, user_id = instance.user_id,
article = instance, article_id = instance.pk)
approved.save()
else:
print("Not Approved")
Views.py
class PendingArticleDetailView( SuccessMessageMixin, LoginRequiredMixin, UpdateView ):
model = Article
template_name = 'adminarticle/article_detail.html'
form_class = ArticleStatusForm
success_message = "Article Updated Successfully"
login_url = 'login-view'
def dispatch(self, request, *args, **kwargs):
if request.user.is_adminuser != True:
return redirect( 'error-404' )
return super().dispatch(request, *args, **kwargs)
def get_success_url( self ):
return reverse( 'view-admin-article', kwargs = { 'pk': self.object.id } )
def get_context_data( self, **kwargs ):
context = super( PendingArticleDetailView, self ).get_context_data( **kwargs )
context[ 'form' ] = ArticleStatusForm( instance = self.get_object() )
context[ 'pending_article' ] = Article.objects.filter( user = self.object.user.id, status = 1 ).count()
context[ 'approved_article' ] = Article.objects.filter( user = self.object.user.id, status = 2 ).count()
context[ 'declined_article' ] = Article.objects.filter( user = self.object.user.id, status = 3 ).count()
return context
def post( self, request, *args, **kwargs ):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid( form )
else:
return self.form_invalid( form )
def form_valid( self, form ):
form.save()
return super( PendingArticleDetailView, self ).form_valid( form )
完成错误跟踪
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/article/article/1/change/
Django Version: 2.1.2
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'django_cleanup',
'django.contrib.humanize',
'password_reset.apps.Password_resetConfig',
'mywriteup.apps.MywriteupConfig',
'myauth.apps.MyauthConfig',
'adminactivities.apps.AdminactivitiesConfig',
'account.apps.AccountConfig',
'article.apps.ArticleConfig',
'wallet.apps.WalletConfig',
'myadmins.apps.MyadminsConfig',
'adminarticle.apps.AdminarticleConfig',
'admintransaction.apps.AdmintransactionConfig',
'adminusers.apps.AdminusersConfig',
'adminupdates.apps.AdminupdatesConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\sites.py" in inner
223. return view(request, *args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in change_view
1639. return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in changeform_view
1525. return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in _changeform_view
1564. self.save_model(request, new_object, form, not add)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in save_model
1091. obj.save()
File "C:\Users\DENIS JOHN\Documents\Projects\django\my_writeup\article\models.py" in save
23. super().save()
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save
718. force_update=force_update, update_fields=update_fields)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save_base
758. update_fields=update_fields, raw=raw, using=using,
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py" in send
175. for receiver in self._live_receivers(sender)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py" in <listcomp>
175. for receiver in self._live_receivers(sender)
File "C:\Users\DENIS JOHN\Documents\Projects\django\my_writeup\article\signals\handlers.py" in add_approved_article
25. article = instance, article_id = instance.pk)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py" in create
413. obj.save(force_insert=True, using=self.db)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save
718. force_update=force_update, update_fields=update_fields)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in _save_table
831. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in _do_insert
869. using=using, raw=raw)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py" in _insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
1288. for sql, params in self.as_sql():
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in as_sql
1241. for obj in self.query.objs
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in <listcomp>
1241. for obj in self.query.objs
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in <listcomp>
1240. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in prepare_value
1182. value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py" in get_db_prep_save
790. return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py" in get_db_prep_value
956. value = self.get_prep_value(value)
File "C:\Users\DENIS JOHN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
965. return int(value)
Exception Type: ValueError at /admin/article/article/1/change/
Exception Value: invalid literal for int() with base 10: 'user'
答案 0 :(得分:0)
可能是在行上使用on_delete = models.SET( "Unknown" )
user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET( "Unknown" ) )
将user
设置为字符串"Unknown"
而不是None
会导致转换错误。
答案 1 :(得分:0)
当您在signal.py中创建ApprovedArticle对象时,您正在传入字符串'user'。
请勿将user_id和article_id传递给create,因为它们由外键填充。
尝试approved = ApprovedArticle.objects.create(user=instance.user, article=instance)
答案 2 :(得分:0)
我知道我的问题来自哪里,但我不知道为什么。问题出在我的model.py init 方法上。我删除了 init 方法,一切正常。
Model.py
class ApprovedArticle(models.Model):
user = models.ForeignKey(User, on_delete=models.SET('Unknown'))
article = models.ForeignKey(Article, on_delete=models.CASCADE)
link = models.CharField(max_length=150)
views = models.CharField(max_length=150, default=0)
link_views = models.CharField(max_length=150, default='NIL')
approved_status = models.ForeignKey(ApprovedArticleStatus, on_delete=models.SET('Uncategorized'),
default=DEFAULT_STATUS)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
added_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.article.title
def __init__(self, *args, **kwargs):
super(ApprovedArticle, self).__init__(*args, *kwargs)
self.original_views = self.views