如何在django中保存多个字段?

时间:2012-02-17 04:48:38

标签: python django django-models many-to-many

models.py:

class Tag(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=500, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now_add=True)

class Post(models.Model):
    user = models.ForeignKey(User)
    tag = models.ManyToManyField(Tag)
    title = models.CharField(max_length=100)
    content = models.TextField()
    created = models.DateTimeField(default=datetime.datetime.now)
    modified = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return '%s,%s' % (self.title,self.content)


class PostModelForm(forms.ModelForm):
    class Meta:
        model = Post


class PostModelFormNormalUser(forms.ModelForm):
    class Meta:
        model = Post
        widgets = { 'tag' : TextInput() }
        exclude = ('user', 'created', 'modified')

    def __init__(self, *args, **kwargs):
        super(PostModelFormNormalUser, self).__init__(*args, **kwargs)      
        self.fields['tag'].help_text = None

我在views.py中试过的:(看起来不正确)

    if request.method == 'POST':
        form = PostModelFormNormalUser(request.POST)
        print form
        print form.errors           
        tagstring = form.data['tag']
        splitedtag = tagstring.split()

        if form.is_valid():
            temp = form.save(commit=False)
            temp.user_id = user.id
            temp.save()
            post = Post.objects.get(id=temp.id)

            l = len(splitedtag)         
            for i in range(l):
                obj = Tag(name=splitedtag[i])
                obj.save()
                post.tag.add(obj)

            post = Post.objects.get(id=temp.id)
            return HttpResponseRedirect('/viewpost/' + str(post.id))

    else:
        form = PostModelFormNormalUser()
        context = {'form':form}
        return render_to_response('addpost.html', context, context_instance=RequestContext(request))

任何人都可以发布示例完整代码编辑,以保存到Post表,Tag表和post_tag表吗?

输入表单将包含一个文本框,用于输入'title'和texarea用于'content',一个文本框用于输入'tag'作为字符串。标签字符串由空格分隔。我需要将这些标记词保存到Tag表中并映射到post_tag表中。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

在关于ModelForms和save(commit=False)的Django文档中,您将找到有关save_m2m() method的信息。我相信这就是你要找的东西。

答案 1 :(得分:2)