简体   繁体   English

我如何在Django中保存Manytomany字段?

[英]How can i save manytomany field in django?

models.py: 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

what i tried in views.py: (that doesn't look the correct way) 我在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))

Can anyone post example complete code editing this to save into Post table, Tag table and post_tag table? 任何人都可以发布示例完整代码来对其进行编辑,以保存到Post表,Tag表和post_tag表中吗?

The input form will contain a textbox to type 'title' and texarea for 'content' and a textbox to type 'tag' as string. 输入表单将包含一个文本框,用于输入“ title”,并在texarea中输入“ content”,以及一个文本框,用于输入“ tag”作为字符串。 The tag string is seperated by space. 标签字符串以空格分隔。 I need to save those tag words into Tag table and map in post_tag table. 我需要将这些标记词保存到Tag表中并映射到post_tag表中。

How can i do this? 我怎样才能做到这一点?

In the Django docs regarding ModelForms and save(commit=False) , you'll find information regarding the save_m2m() method . 在有关ModelForms和save(commit=False)的Django文档中,您将找到有关save_m2m()方法的信息 I believe that is what you're looking for. 我相信这就是您要寻找的。

As an aside, if you're implimenting tagging, you could just use django-tagging or django-taggit 顺便说一句,如果您要添加标签,则可以只使用django-tagging或django-taggit

http://code.google.com/p/django-tagging/ http://code.google.com/p/django-tagging/

http://django-taggit.readthedocs.org/en/latest/index.html http://django-taggit.readthedocs.org/en/latest/index.html

http://djangopackages.com/grids/g/tagging/ http://djangopackages.com/grids/g/tagging/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM