#python #django
#python #django
Вопрос:
Я новичок в django, и я создал модель и сигнал, при изменении поля он должен инициировать сигнал и создать новую запись в другой модели с идентификатором пользователя, но это выдает мне эту ошибку… Когда я меняю статус на approved, предполагается, что сигнал создает новый объект в объекте 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:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocorehandlersexception.py" in inner
34. response = get_response(request)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocorehandlersbase.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocorehandlersbase.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocontribadminoptions.py" in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangoutilsdecorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangoviewsdecoratorscache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocontribadminsites.py" in inner
223. return view(request, *args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocontribadminoptions.py" in change_view
1639. return self.changeform_view(request, object_id, form_url, extra_context)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangoutilsdecorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangoutilsdecorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocontribadminoptions.py" in changeform_view
1525. return self._changeform_view(request, object_id, form_url, extra_context)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocontribadminoptions.py" in _changeform_view
1564. self.save_model(request, new_object, form, not add)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangocontribadminoptions.py" in save_model
1091. obj.save()
File "C:UsersDENIS JOHNDocumentsProjectsdjangomy_writeuparticlemodels.py" in save
23. super().save()
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsbase.py" in save
718. force_update=force_update, update_fields=update_fields)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsbase.py" in save_base
758. update_fields=update_fields, raw=raw, using=using,
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodispatchdispatcher.py" in send
175. for receiver in self._live_receivers(sender)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodispatchdispatcher.py" in <listcomp>
175. for receiver in self._live_receivers(sender)
File "C:UsersDENIS JOHNDocumentsProjectsdjangomy_writeuparticlesignalshandlers.py" in add_approved_article
25. article = instance, article_id = instance.pk)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsmanager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsquery.py" in create
413. obj.save(force_insert=True, using=self.db)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsbase.py" in save
718. force_update=force_update, update_fields=update_fields)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsbase.py" in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsbase.py" in _save_table
831. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsbase.py" in _do_insert
869. using=using, raw=raw)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsmanager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsquery.py" in _insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelssqlcompiler.py" in execute_sql
1288. for sql, params in self.as_sql():
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelssqlcompiler.py" in as_sql
1241. for obj in self.query.objs
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelssqlcompiler.py" in <listcomp>
1241. for obj in self.query.objs
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelssqlcompiler.py" in <listcomp>
1240. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelssqlcompiler.py" in prepare_value
1182. value = field.get_db_prep_save(value, connection=self.connection)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsfields__init__.py" in get_db_prep_save
790. return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsfields__init__.py" in get_db_prep_value
956. value = self.get_prep_value(value)
File "C:UsersDENIS JOHNAppDataLocalProgramsPythonPython37libsite-packagesdjangodbmodelsfields__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'
Комментарии:
1. Я только что отредактировал свой вопрос и добавил трассировку ошибки
2. удален downvote
Ответ №1:
Это может быть использование on_delete = models.SET( "Unknown" )
в строке
user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET( "Unknown" ) )
Установка user
в строку "Unknown"
вместо None
приведет к ошибке преобразования.
Комментарии:
1. Я изменил его на on_delete=models. УСТАНОВЛЕНО (Нет), но по-прежнему выдает ту же ошибку, я даже удалил все свои старые файлы миграции и базу данных, но все еще не работает.
Ответ №2:
Я видел, откуда возникла моя проблема, но я не знаю почему. проблема была в моем model.py метод инициализации. Я удалил метод 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