![](/img/trans.png)
[英]After reinstalling Django due to computer crash, I am getting following error when I try to access the models in my app
[英]Why is the django admin area throwing an error when I try to access my app?
我已經啟動了博客應用程序。 該模型如下所示:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=512)
image = models.ImageField(upload_to='/pathto/blogImages')
body = models.TextField()
visible = models.BooleanField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
class Tag(models.Model):
keyword = models.CharField(max_length=256)
posts = models.ManyToManyField(Post)
def __unicode__(self):
return self.keyword
運行syncdb之后,我然后創建了一個如下所示的admin.py文件:
from blog.models import Post
from blog.models import Tag
from django.contrib import admin
class TagInline(admin.TabularInline):
model = Tag
extra = 3
class PostAdmin(admin.ModelAdmin):
inlines = [TagInline]
admin.site.register(Post, PostAdmin)
當我訪問管理區域(http:// localhost:8000 / admin / blog / post / add /)時,出現以下錯誤:
Exception at /admin/blog/post/add/
<class 'blog.models.Tag'> has no ForeignKey to <class 'blog.models.Post'>
Request Method: GET
Request URL: http://localhost:8000/admin/blog/post/add/
Django Version: 1.4.1
Exception Type: Exception
Exception Value:
<class 'blog.models.Tag'> has no ForeignKey to <class 'blog.models.Post'>
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in _get_foreign_key, line 800
Python Executable: /usr/bin/python
Python Version: 2.7.3
當我在django中查找多對多關系時,發現https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/ 。 我一直找不到我想要的東西。 如何避免該錯誤?
當您處理多對多關系時, InlineModelAdmin
應該如下所示 :
class TagInline(admin.TabularInline):
model = Tag.posts.through
也許您可以嘗試將帖子的模型字段設置為
posts = models.ManyToManyField(Post, null=True, blank=True)
。
我猜可能不會創建該帖子,因此它無法創建標簽或將標簽“連接”到該帖子。
您的多對多字段應位於帖子模型上,而不是標簽模型上。 必須按順序定義對象或必須建模。ManyToManyField('tag')除非不可避免,否則不建議這樣做。 因此,請先定義標簽,然后再發布,這樣您就可以在發布模型下使用(tag)。 我建議只使用django標記。 它一直為我服務。
畢竟,這就是使Django如此吸引人的原因在於可重用的應用程序和快速的開發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.