django - django-taggit 表单 [英] django - django-taggit form

查看:36
本文介绍了django - django-taggit 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 django-taggit(点击这里).文档( 点击此处)谈到使用 ModelForm 生成表单,但我已经有了想要使用的表单.

I would like to use django-taggit (click here ). The documentation ( click here) talks about using ModelForm to generate the form but I have already my form that I would like to use.

假设我有这样的事情:

forms.py

class MyForm(forms.Form):
    ......
    tags = forms.CharField(max_length=200, widget=forms.Textarea)

如何保存来自 tags 字段的标签?我的 views.py 中有什么?一个真实的例子将不胜感激.

how do I save the the tags coming from the tags field? What goes in my views.py? A real example would be truly appreciated.

推荐答案

我对 django taggit 应用程序不太熟悉,但看起来如果你想使用应用程序使用的相同字段和小部件设置,你可以从 taggit.forms (https://github.com/alex/django-taggit/blob/master/taggit/forms.py):

I'm not too familiar with the django taggit app, but it looks like if you want to use the same field and widget setup the app uses, you can import them from the taggit.forms (https://github.com/alex/django-taggit/blob/master/taggit/forms.py):

你的models.py:

your models.py:

from django.db import models

from taggit.managers import TaggableManager

class Food(models.Model):
    name = models.CharField(max_length=20)

    tags = TaggableManager()

你的 forms.py

your forms.py

from taggit.forms import *

class MyForm(forms.Form):
    name = forms.CharField()
    m_tags = TagField()

TagField 将使用 taggit 应用程序中 utils.py 的 parse_tags 方法返回处理后的输入.返回看起来是一个清理过的列表(set(words))

The TagField will return the processed input using the parse_tags method from utils.py in the taggit app. The return looks to be a cleaned up list(set(words))

你的views.py

if form.is_valid():
    name = form.cleaned_data['name']
    m_tags = form.cleaned_data['m_tags']
    object = Food(name=name)
    object.save()
    for m_tag in m_tags:
        object.tags.add(m_tag)
    return HttpResponseRedirect('/thanks/')

这篇关于django - django-taggit 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆