I wanted to add tags to my blog in the same way as a category, unfortunately during "makemigrations" I got an error:
"django.db.utils.OperationalError: no such table: theblog_tag"
Then I tried every way I found, removed the migrations (except init.py) and db.sqlite3 and tried to do the migrations again. Unfortunately for now, the bug also affects the categories.
Here is traceback:
Traceback (most recent call last):
File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\plantblog\virt\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in
execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: theblog_category
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\plantblog\blogplant\manage.py", line 22, in <module>
main()
File "C:\plantblog\blogplant\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\plantblog\virt\lib\site-packages\django\core\management\__init__.py", line 419, in
execute_from_command_line
utility.execute()
File "C:\plantblog\virt\lib\site-packages\django\core\management\__init__.py", line 413, in
execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 354, in
run_from_argv
self.execute(*args, **cmd_options)
File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 393, in
execute
self.check()
File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 419, in check
all_issues = checks.run_checks(
File "C:\plantblog\virt\lib\site-packages\django\core\checks\registry.py", line 76, in
run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\plantblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in
check_url_config
return check_resolver(resolver)
File "C:\plantblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in
check_resolver
return check_method()
File "C:\plantblog\virt\lib\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "C:\plantblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\plantblog\virt\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\plantblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\plantblog\virt\lib\site-packages\django\urls\resolvers.py", line 591, in
urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Gryzelda\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:\plantblog\blogplant\blogplant\urls.py", line 8, in <module>
path('', include('theblog.urls')),
File "C:\plantblog\virt\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\Gryzelda\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:\plantblog\blogplant\theblog\urls.py", line 3, in <module>
from .views import HomeView, PostDetailView, AddPostView, UpdatePostView, DeletePostView,
CategoryView, TagView
File "C:\plantblog\blogplant\theblog\views.py", line 5, in <module>
from .forms import PostForm, EditForm
File "C:\plantblog\blogplant\theblog\forms.py", line 7, in <module>
for item in choices:
File "C:\plantblog\virt\lib\site-packages\django\db\models\query.py", line 280, in __iter__
self._fetch_all()
File "C:\plantblog\virt\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\plantblog\virt\lib\site-packages\django\db\models\query.py", line 140, in __iter__
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch,
chunk_size=self.chunk_size)
File "C:\plantblog\virt\lib\site-packages\django\db\models\sql\compiler.py", line 1124, in
results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
File "C:\plantblog\virt\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in
execute_sql
cursor.execute(sql, params)
File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 75, in
_execute_with_wrappers
return executor(sql, params, many, context)
File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\plantblog\virt\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\plantblog\virt\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in
execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: theblog_category
And here is my code:
views.py
class HomeView(ListView):
model = Post
paginate_by = 2
template_name = 'home.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
tag_menu = Tag.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
paginator = Paginator(cat_menu, self.paginate_by)
page = self.request.GET.get('page')
try:
pages = paginator.page(page)
except PageNotAnInteger:
pages = paginator.page(1)
except EmptyPage:
pages = paginator.page(paginator.num_pages)
context["tag_menu"] = tag_menu
context["cat_menu"] = pages
return context
def CategoryView(request, cats):
cat_posts = Post.objects.filter(category__iexact=cats.replace('-', ' ').replace('roj','RÓJ'))
context = {}
context['cats'] = cats.title().replace('-', ' ').replace('roj','rój')
context['cat_posts'] = cat_posts
cat_menu = Category.objects.all()
context["cat_menu"] = cat_menu
return render(request, 'categories.html', context)
def TagView(request, tags):
tag_posts = Post.objects.filter(tag__iexact=tags.replace('-', ' ').replace('roj','RÓJ'))
context = {}
context['tags'] = tags.title().replace('-', ' ').replace('roj','rój')
context['tag_posts'] = tag_posts
tag_menu = Tag.objects.all()
context["tag_menu"] = tag_menu
return render(request, 'tags.html', context)
class PostDetailView(DetailView):
model = Post
template_name = 'post_details.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
tag_menu = Tag.objects.all()
context = super(PostDetailView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
context["tag_menu"] = tag_menu
return context
urls
urlpatterns = [
path('', HomeView.as_view(), name="home"),
path('post/<int:pk>', PostDetailView.as_view(), name='post-detail'),
path('post/add', AddPostView.as_view(),name='add_post'),
path('post/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'),
path('post/delete/<int:pk>', DeletePostView.as_view(), name='delete_post'),
path('about-me', views.aboutme, name='aboutme'),
path('contact.html', views.contact, name='contact'),
path('category/<str:cats>', CategoryView, name='category'),
path('search-blogs/', views.BlogSearchView.as_view(), name='search_blogs'),
path('tag/<str:tags>', TagView, name='tag'),
]
models
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('home')
class Tag(models.Model):
namee = models.CharField(max_length=255)
def __str__(self):
return self.namee
def get_absolute_url(self):
#return reverse('post-detail', args=(str(self.id)))
return reverse('home')
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null = True, blank=True, upload_to="images/" )
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='brak kategorii' )
tag = models.CharField(max_length=255)
class Meta:
ordering = ['-id']
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('home')
forms
choices = Category.objects.all().values_list('name','name')
choice_list = []
for item in choices:
choice_list.append(item)
tags = Tag.objects.all().values_list('namee','namee')
tag_list = []
for it in tags:
tag_list.append(it)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'title_tag', 'author', 'category', 'tag', 'body', 'header_image')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'title_tag': forms.TextInput(attrs={'class': 'form-control'}),
'author': forms.Select(attrs={'class': 'form-control'}),
'category': forms.Select(choices=choice_list, attrs={'class': 'form-control'}),
'tag': forms.Select(choices=tag_list, attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
}
Django is initializing all your imports starting from your urls.py file which leads back to your forms.py file, this is the offending code:
choices = Category.objects.all().values_list('name','name')
choice_list = []
for item in choices:
choice_list.append(item)
tags = Tag.objects.all().values_list('namee','namee')
tag_list = []
Django is trying to make the query to the table category upon startup which doesn't exist in the database yet, unfortunately this also prevents actions such as makemigrations, so override the forms init function and place the code there.
Something like this:
class PostForm(forms.ModelForm):
.....
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
choices = Category.objects.all().values_list('name','name')
choice_list = []
for item in choices:
choice_list.append(item)
self.fields['category'].choices = choice_list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.