python - Django CreateView is not saving object -
i'm practicing django class-based-view basic blog application. reason, however, createview post model not saving post inside 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 error, when check admin page, post created createview not saved in database.. idea..??
thanks
one tip: don't use exclude
when defining forms, use fields
, more secure , recommended way it.
the redirect defined get_success_url
method. if have in model method get_absolute_url
createview redirect url, otherwise can override get_success_url
in 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 find page useful when working cbvs: http://ccbv.co.uk/projects/django/1.5/django.views.generic.edit/createview/
Comments
Post a Comment