Django:" ValueError:基数为10的int()的无效文字:"将对象添加到Category时

时间:2017-11-29 06:29:48

标签: python django

我是Django的初学者。我想在我的Django博客中添加一个添加类别的选项。但是,我收到了这个错误:

  

ValueError:基数为10的int()的无效文字:'类别'

这里是我在models.py中使用的代码:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
#from tinymce import HTMLField
#from froala_editor.fields import FroalaField
from redactor.fields import RedactorField



class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')

class Category(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=250, verbose_name="Title")

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']

    def __str__(self):
        return self.title

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, related_name='blog_posts')
    content = RedactorField(verbose_name=u'Text')
    publish = models.DateTimeField(default=timezone.now)
    category = models.ForeignKey(Category, verbose_name="Category", default='category')
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

    objects = models.Manager() # The default manager.
    published = PublishedManager() # The Dahl-specific manager.

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year,
                                                 self.publish.strftime('%m'),
                                                 self.publish.strftime('%d'),
                                                 self.slug])



class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return 'Comment by {} on {}'.format(self.name, self.post)

请你帮我解决这个问题吗? 基本上,我正在尝试构建一个与WordPress非常相似的博客。它应该有添加类别和标签的选项。

更新
我已通过以下方式更改了类别:

category = models.ForeignKey(Category, verbose_name="Category", null=True, blank=True)

但是现在,我收到了这个错误:

  

在/ blog /没有这样的表的操作错误:blog_post

这是追溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/blog/

Django Version: 1.11.6
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'tinymce',
 'redactor']
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']


Template error:
In template C:\Windows\SysWOW64\mysite\blog\templates\blog\base.html, error at line 6
   no such table: blog_post   1 : <! ---- https://www.elementcycles.net/ ---!>
   2 : <!--https://www.catscarf.com-->
   3 : {% load staticfiles %}
   4 : <html>
   5 : <head>
   6 :      <title>{% block titl e %}{% endblock %}</title>
   7 :     
   8 :         <!-- Bootstrap core CSS -->
   9 :      <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
   10 :         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   11 :         
   12 :         <!-- FontAwesome icon fonts -->
   13 :         <link href="{% static "/css/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet">
   14 :         
   15 :         <!-- Google Fonts -->
   16 :         <link href='https://fonts.googleapis.com/css?family=Raleway:400,700' rel='stylesheet' type='text/css'>


Traceback:

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

The above exception (no such table: blog_post) was the direct cause of the following exception:

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Windows\SysWOW64\mysite\blog\views.py" in post_list
  12.     return render(request, 'blog/post/list.html', {'posts': posts})

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  207.                     return self._render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  173.             len_values = len(values)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in __len__
  232.         self._fetch_all()

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in _fetch_all
  1118.             self._result_cache = list(self._iterable_class(self))

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in __iter__
  53.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  894.             raise original_exception

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  884.             cursor.execute(sql, params)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute
  80.             return super(CursorDebugWrapper, self).execute(sql, params)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py" in reraise
  685.             raise value.with_traceback(tb)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /blog/
Exception Value: no such table: blog_post

2 个答案:

答案 0 :(得分:1)

您的默认值是错误的。 category是ForeignKey。为ForeignKeys添加默认值是不好的。 foreginkey值总是整数。相关模型的ID。

答案 1 :(得分:0)

default ='category'在模型'post'中导致错误,因为FK存储为整数。通常我们不使用Fk默认值。也许将其设置为null = True,blank = True。

category = models.ForeignKey(Category, verbose_name="Category", null=True, blank=True)

如果类别不是必填字段,则会出现上述答案。如果需要,只需从现有代码中删除模型“post”的类别字段中的“default ='category'”。