我正在尝试在管理表单上使用autocomplete_light和taggit。
我已阅读有关集成自动完成灯和taggit here的文档, 以及有关在管理员here中集成自动填充灯的文档。但似乎很少(或没有)讨论同时做两件事。
到目前为止我得到了什么。
在models.py
:
from django.db import models
from taggit.managers import TaggableManager
from taggit.models import TagBase, GenericTaggedItemBase
class MyTag(TagBase):
description = models.CharField(max_length = 250, blank = True, null = True)
class MyTagThroughModel(GenericTaggedItemBase):
tag = models.ForeignKey(MyTag, related_name = "tagged_items")
class MyModel(models.Model):
Name = models.CharField(max_length = 200)
...
tags = TaggableManager(through = MyTagThroughModel)
在autocomplete_light_registry.py
:
import autocomplete_light
from models import MyTag
autocomplete_light.register(MyTag)
我打算如何构建admin.py
?
如果这是非管理员表单,则该字段将显示为:
tags = TagField(widget = TagWidget('MyTagAutocomplete'))
如果这是一个非taggit管理表单,我会将以下内容添加到admin模型类中:
form = autocomplete_light.modelform_factory(MyTag)
我如何将两者合并?
答案 0 :(得分:5)
我打算如何构建admin.py?
以下是自动填充代码的示例。它向您展示了autocomplete_light和taggit如何在管理员和非管理员表单上工作。
<强> models.py 强>
from django.db import models
from taggit.managers import TaggableManager
class MyModel(models.Model):
name = models.CharField(max_length = 200)
tags = TaggableManager(blank=True)
<强> autocomplete_light_registry.py 强>
import autocomplete_light
from taggit.models import Tag
autocomplete_light.register(Tag)
<强> forms.py 强>
from django import forms
import autocomplete_light
from autocomplete_light.contrib import taggit_tagfield
from models import MyModel
class MyModelForm(forms.ModelForm):
tags = taggit_tagfield.TagField(widget=taggit_tagfield.TagWidget('TagAutocomplete'))
class Meta:
model = MyModel
widgets = {
'tags': autocomplete_light.TextWidget('TagAutocomplete'),
}
<强> admin.py 强>
from django.contrib import admin
import autocomplete_light
from models import MyModel
from forms import MyModelForm
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
model = MyModel
admin.site.register(MyModel, MyModelAdmin)
<强> views.py 强>
from django.views.generic.edit import CreateView
from models import MyModel
from forms import MyModelForm
class CreateMyModel(CreateView):
model = MyModel
form_class = MyModelForm
<强> urls.py 强>
from django.conf.urls import patterns, url
from views import CreateMyModel
urlpatterns = patterns('',
url(r'^create/$', CreateMyModel.as_view()),
)
quick docs似乎比您正在查看的文档更容易理解。
答案 1 :(得分:3)