gpt4 book ai didi

Django 自动完成灯、taggit 和管理界面

转载 作者:行者123 更新时间:2023-12-01 09:27:18 24 4
gpt4 key购买 nike

我正在尝试在管理表单上使用 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 管理表单,我会将以下内容添加到管理模型类中:
form = autocomplete_light.modelform_factory(MyTag)

我怎样才能将两者结合起来?

最佳答案

How am I meant to structure admin.py?



这是自动完成标签的示例。它向您展示了 autocomplete_light 和 taggit 如何在管理员和非管理员表单上工作。

模型.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)

View .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似乎比您正在查看的文档更容易理解。

关于Django 自动完成灯、taggit 和管理界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com