首页 > 解决方案 > 如何从表单中的用户获取标签并将其保存到 django 中的数据库

问题描述

我有一个表单,它从用户那里获取一些字段和标签,并将用户输入数据保存在数据库中:顺便说一下,我正在使用 taggit

这是我的模型:

from taggit.managers import TaggableManager


class Question(models.Model):
    title = models.CharField(max_length=500)
    name = models.CharField(max_length=50, default=None)
    slug = models.SlugField(max_length=500, unique_for_date='created', allow_unicode=True)
    body = models.TextField(max_length=2000)
    created = models.DateTimeField(auto_now_add=True)
    tags = TaggableManager()

    def get_absolute_url(self):
        return reverse("questions:question_detail", args=[self.created.year, self.created.month, self.created.day, self.slug])
        
    def __str__(self):
        return self.title

这是我的观点:

def question_form(request):

    new_question = None

    if request.method == 'POST':
        question_form = QuestionForm(data=request.POST)
        if question_form.is_valid():
            new_question = question_form.save(commit=False)
            new_question.slug = slugify(new_question.title)
            new_question.save()
            question_form.save_m2m()
    else:
        question_form = QuestionForm()
    
    return render(request, 
                'questions/que/form.html',
                {'question_form':question_form, 'new_question':new_question})

我的 form.py 是这样的:

from taggit.forms import TagField



class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ('name', 'title', 'body',)
    tags = TagField()

我的问题是当用户输入标签和其他字段时,除标签外,所有内容都保存在数据库中!谁能帮我?

标签: djangotagsdjango-taggit

解决方案


推荐阅读