如何从表单中的用户获取标签并将其保存到django中的数据库

问题描述 投票:0回答:1

我有一个表单,可以从用户那里获取一些字段和标签并将用户输入数据保存在数据库中: 顺便说一句,我正在使用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()

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

django tags django-taggit
1个回答
0
投票

在view.py中使用form.save_m2m():

   if form.is_valid():
        doc = form.save(commit=False)
        doc.user = request.user
        doc.save()
        form.save_m2m()
© www.soinside.com 2019 - 2024. All rights reserved.