django - django-taggit form

前端 未结 3 903
南方客
南方客 2020-12-29 12:40

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 13:24

    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):

    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()
    

    your forms.py

    from taggit.forms import *
    
    class MyForm(forms.Form):
        name = forms.CharField()
        m_tags = TagField()
    

    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))

    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/')
    

提交回复
热议问题