我正在使用django-taggit(https://github.com/alex/django-taggit)。为了让用户添加标签,我使用一个表格字段,我将其转换为标签并添加它们。
但是,当我尝试加载模板进行编辑时。我在我的栏中获得了taggit对象。 现在我想再次转换为普通可读字符串。 但是,在将实例传递给我的表单之前,我似乎无法编辑该实例的字段。
表格:
class NewCampaignForm(forms.ModelForm):
""" Create a new campaign and add the searchtags """
queryset = Game.objects.all().order_by("name")
game = forms.ModelChoiceField(queryset=queryset, required=True)
tags = forms.CharField(required=False)
focus = forms.ChoiceField(required=False, choices=Campaign.CHOICES)
class Meta:
model = Campaign
fields = ["game", "tags", "focus"]
exclude = ["owner"]
我的模特:
class Campaign(models.Model):
""" campaign information """
ROLEPLAY = "Roleplay"
COMBAT = "Combat"
BOTH = "Both"
CHOICES = (
(ROLEPLAY, "Roleplay"),
(COMBAT, "Combat"),
(BOTH, "Both"),
)
owner = models.ForeignKey(User)
game = models.ForeignKey(Game)
focus = models.CharField(max_length=15, choices=CHOICES)
tags = TaggableManager()
视图:
def campaign_view(request, campaign_id):
campaign = get_object_or_404(Campaign, pk=campaign_id)
campaign.tags = "Some string"
new_campaign_form = NewCampaignForm(instance=campaign)
但是当我尝试这个时,我仍然在我的输入字段中获取taggit对象([])而不是“Some string” 我应该如何解决这个问题
答案 0 :(得分:0)
我不确定我是如何忽视这一点的。但这有效:
new_campaign_form = NewCampaignForm(instance=campaign, initial={"tags": "Some String"})
对不起,应该看得更多并且尝试更好