Django CreateView is not saving object

user2492270 picture user2492270 · Jul 24, 2013 · Viewed 10.3k times · Source

I'm practicing django Class-Based-View with a basic blog application. For some reason, however, the CreateView for my Post model is not saving the post inside the database.

models.py

class Post(models.Model):
    user = models.ForeignKey(User)
    post_title = models.CharField(max_length=200)
    post_content = models.CharField(max_length=500)
    post_date = models.DateTimeField('date posted')

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ('user', 'post_date')

views.py

class PostCreate(CreateView):
    template_name = 'app_blog/post_save_form.html'
    model = Post
    form_class = PostForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.post_date = datetime.now()
        return super(PostCreate, self).form_valid(form)

It displays content without generating any error, but when I check the admin page, the post created by the CreateView is not saved in the database.. Any idea..??

Thanks

Answer

Diego Navarro picture Diego Navarro · Jul 24, 2013

One tip: don't use exclude when defining forms, use fields, is more secure and the recommended way to do it.

The redirect is defined by get_success_url method. If you have in your model the method get_absolute_url CreateView will redirect to that URL, otherwise you can always override get_success_url in your view.

Using get_absolute_url:

class Post(models.Model):
    user = models.ForeignKey(User)
    post_title = models.CharField(max_length=200)
    post_content = models.CharField(max_length=500)
    post_date = models.DateTimeField('date posted')

    @permalink
    def get_absolute_url(self):
        return ('myurlname', (), {'myparam': something_useful})

Using get_success_url:

class PostCreate(CreateView):
    template_name = 'app_blog/post_save_form.html'
    model = Post
    form_class = PostForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.post_date = datetime.now()
        form.save()
        return super(PostCreate, self).form_valid(form)

    def get_success_url(self):
        return reverse('myurlname', args=(somethinguseful,))

I think you will find this page very useful when working with CBVs: http://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/CreateView/