本文介绍了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)

如何保存来自标签字段的标签?我的 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导入它们():

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将使用parse_返回已处理的输入taggit应用程序中的utils.py的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

your 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表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:49