cola
cola

Reputation: 12466

How can i save manytomany field in django?

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)

    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?

The input form will contain a textbox to type 'title' and texarea for 'content' and a textbox to type 'tag' as string. The tag string is seperated by space. I need to save those tag words into Tag table and map in post_tag table.

How can i do this?

Upvotes: 0

Views: 5475

Answers (2)

powlo
powlo

Reputation: 2688

As an aside, if you're implimenting tagging, you could just use django-tagging or django-taggit

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

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

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

Upvotes: 2

James Addison
James Addison

Reputation: 3094

In the Django docs regarding ModelForms and save(commit=False), you'll find information regarding the save_m2m() method. I believe that is what you're looking for.

Upvotes: 3

Related Questions