Reputation: 5174
I strongly suspect that this boils down to me needing to understand some language construct better, but I don't know where to start, so I'm just going to have to throw some code out.
models:
class BlogTag(models.Model):
tag = models.CharField(max_length=255)
def __unicode__(self):
return self.tag
class BlogEntry(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField()
tags = models.ManyToManyField(BlogTag)
def __unicode__(self):
return self.title
form:
class BlogForm(ModelForm):
class Meta:
model = BlogEntry
view:
title='New Blog Entry'
if request.method=='POST':
form=BlogForm(request.POST)
if form.is_valid():
cd=form.cleaned_data
blogEntry=BlogEntry(**cd)
blogEntry.save()
else:
form=BlogForm();
return render_to_response('blog_add.html', locals())
By using **cd I was able to take the cleaned data directly into my object, which is obviously desireable because this way the view is loosely coupled to the other objects -- I can change the model, and everything else changes with it without me having to do a thing.
Unfortunately, I'm getting an error that:
'tags' is an invalid keyword argument for this function
I could always break down the CD and build a manual dictionary approach of blogEntry=BlogEntry(title=cd['title']...) and then just add the tags in one by one, but... I should have better options than that, and I just don't know what they are :(
Upvotes: 0
Views: 442
Reputation: 11464
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
if request.method == 'POST':
form = BlogForm(request.POST)
if form.is_valid():
blogEntry = form.save()
# redirect ..
else:
form = BlogForm()
context = {
"form": form,
# ...
}
return render_to_response('blog_add.html', context)
PS, locals()
is bad form and http://www.python.org/dev/peps/pep-0008/
Upvotes: 1
Reputation: 5058
I think what it boils down to is that **cd
will pass in the arguments as a dictionary. BlogEntry
is expecting a BlogTag
type for tags
instead you are passing it the dictionary argument which is not the right type. First create a BlogTag
object and then pass that in to BlogEntry
This might help http://anubis.blasux.ru/books/Python/www.djangoproject.com/documentation/0.96/models/many_to_many/
Upvotes: 1