更新时间:2023-12-04 09:30:22
提示:请勿使用 exclude
在定义表单时,请使用 fields
,这是更安全的方法,也是推荐的做法。
One tip: don't use exclude
when defining forms, use fields
, is more secure and the recommended way to do it.
重定向是通过 get_success_url
方法定义的。如果您的模型中有方法 get_absolute_url
CreateView 将重定向到该URL,否则您始终可以覆盖 get_success_url
。
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.
使用 get_absolute_url
:
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})
使用 get_success_url
:
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,))
我认为您在使用CBV时会发现此页面非常有用:
http://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/CreateView/
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/