Aleksander Monk
Aleksander Monk

Reputation: 2907

'categories' is an invalid keyword argument for this function , django

So , I'm writing blog and I have class Category and class Post

class Category(models.Model):
    title = models.CharField(max_length=65)
    slug = models.SlugField(unique=True)
    description = models.TextField(max_length=155)


class Post(models.Model):
    author = models.ForeignKey(User)
    categories = models.ManyToManyField(Category)
    title = models.CharField(max_length=65)
    slug = models.SlugField(unique=True)
    description = models.TextField(max_length=155)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)

When I want to add new post , I have this error

Exception Value: 'categories' is an invalid keyword argument for this function

This is what I have in views.py and what should add new post to database

def post_new(request):
    if request.user.is_authenticated():
        form = PostForm(request.POST or None)
        if form.is_valid():
            cd = form.cleaned_data
            post = Post(title=cd['title'], content=cd['content'],
                        description=cd['description'],
                        categories=cd['categories'],
                        author=User.objects.get_by_natural_key(request.user.get_username()))
            post.save()
            return redirect(post)
    return render_to_response('post_edit.html', {'form': PostForm(request.POST or None)},
                              context_instance=RequestContext(request))

What is wrong here?

Upvotes: 0

Views: 1008

Answers (1)

sax
sax

Reputation: 3806

(I suppose PostForm is a ModelForm)

you can save the form directly and have a Post instance back. simply use

 post = form.save(commit=False)
 post.author = request.user
 post.save() 

see https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

the reason of your error is that you can not add an object to a M2M field until it has been saved

Upvotes: 3

Related Questions