ManyToManyField breaking in Admin screens and shouldn't be

时间秒杀一切 提交于 2020-03-25 15:17:22

问题


I have some models like this:

class Category(models.Model):
    class Meta:
        ordering = ['name']

    name = models.CharField(max_length=100)
    text = models.TextField(blank=True)

    def __str__(self):
        return self.name

class Tag(models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name

class Tool(models.Model):
    name = models.CharField(max_length=30, null=True, default='')   
    url = models.URLField(max_length=250, null=True, default='')
    image_url = models.URLField(max_length=250, null=True, default='', blank=True)
    about = models.TextField(default='', null=True, blank=True)
    tags = models.ManyToManyField( Tag, related_name="tools" , blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category1")
    altcategory = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category2")

And everything seem ok, except when I go to add a tag to a Tool in the Admin screens. I can create a Tool and Tag but when I select a tag in the taglist in the Admin screens and Save I get:

The above exception (syntax error at or near "ON" LINE 1: ...ls_tool_tags" ("tool_id", "tag_id") VALUES (1, 2) ON CONFLIC... ^ ) was the direct cause of the following exception:

with the sql:


('INSERT INTO "tools_tool_tags" ("tool_id", "tag_id") VALUES (%s, %s) ON '
 'CONFLICT DO NOTHING')

The DEBUG screen is saying the error is at "tag_id", is strange...

I hope it's not a version thing, since I'm using Heroku and have been really impressed with how everything "just works". My Django version is '3.0.4' and Postgres 12.2.


回答1:


I don't think ManyToMany works out of the box. So I had to create a "through" model... and change the admin form to this...

models.py

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.auth.models import User
from django.utils.html import format_html
from django.contrib.contenttypes.models import ContentType

class Category(models.Model):
    class Meta:
        ordering = ['name']

    name = models.CharField(max_length=100)
    text = models.TextField(blank=True)

    def __str__(self):
        return self.name



class Tag(models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name

class Tool(models.Model):
    name = models.CharField(max_length=30, null=True, default='')   
    url = models.URLField(max_length=250, null=True, default='')
    image_url = models.URLField(max_length=250, null=True, default='', blank=True)
    about = models.TextField(default='', null=True, blank=True)
    tags = models.ManyToManyField( 
        Tag, 
        through="PageTags",
        through_fields=('tool', 'tag'))

    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category1")
    altcategory = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category2")

    def _get_thumbnail(self):
        return format_html(u'<img src="{}" width="150"/>', self.image_url)
    _get_thumbnail.allow_tags = True

    def _get_link(self):
        return format_html(u'<a href="{}" target="_blank"/>{}</a>', self.url, self.url)
    _get_link.allow_tags = True

    def __str__(self):
        return self.name + ": " + self.url

class PageTags(models.Model):

    tag = models.ForeignKey(Tag ,   on_delete=models.CASCADE, )
    tool= models.ForeignKey(Tool ,  on_delete=models.CASCADE, )
    amount = models.IntegerField(default=0)

... and admin.py to this...

from django.contrib import admin
from django.contrib.admin import TabularInline 
#from django.contrib.contenttypes.admin import  GenericTabularInline

from django.utils.html import format_html_join
from django.utils.safestring import mark_safe

from .models import Tool, Category, Tag, PageTags


class PageTagsInline(admin.TabularInline): 
    model = PageTags
    extra = 1


class ToolAdmin(admin.ModelAdmin):
    #fields = ('name', )

    list_display = ('name','_get_link','category','altcategory', "_get_thumbnail", )
    list_filter = ('category',)
    search_fields = ['name', "about"]
    filter_horizontal = ('tags',)
    inlines = [PageTagsInline,]


admin.site.register(Tag)
admin.site.register(Category)
admin.site.register(Tool, ToolAdmin)

And the interface is different, not like the permissions widgets, but OK... at least not bombing the admin.



来源:https://stackoverflow.com/questions/60625639/manytomanyfield-breaking-in-admin-screens-and-shouldnt-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!