django从表单中保存数据

时间:2014-05-25 19:57:36

标签: python django forms

我想在问题中添加标签。而不是这个,问题标题改为list_tags的内容。

例如:

class NewAskForm(forms.Form):
    title = forms.CharField(max_length=80)
    content_question = forms.CharField()
    tags = forms.CharField(max_length=200, required=False)

def newask(request):
    if request.method == 'POST':
        form = NewAskForm(request.POST)
    if form.is_valid():
        newask = Question(title = form.cleaned_data['title'])
        newask.content_question = form.cleaned_data['content_question']
        newask.id_user_id = request.user.id
        newask.creation_date_question = datetime.now()
        list_tags = form.cleaned_data['tags']
        new_tag = Tag(content_tag = list_tags.split(',', 1))
        new_tag.save()
        newask.save()
        newask.tags.add(new_tag)
        return HttpResponseRedirect('/ask')
    else:
        form = NewAskForm()

    return render(request, 'ask/newask.html', {'form': form })

我做错了什么?

class Tag(models.Model):
    content_tag = models.CharField(max_length=20)
    def __unicode__(self):  
        return self.content_tag

class Question(models.Model):
    tags = models.ManyToManyField(Tag, related_name='tags')

0 个答案:

没有答案