未调用 CreateView 中的 Django form_valid() 和 form_invalid()
Django form_valid() and form_invalid() in CreateView not called
我目前正在使用 django 的 CreateView post 数据到数据库。不幸的是,我想保存和执行自定义逻辑的方法 form_valid() 从未被调用过。我在另一个堆栈溢出响应中读到 form_invalid() 可能会发现问题,但我无法调用该方法。似乎调用的唯一方法是 get(),我覆盖了它并在其中放入了打印语句。我做错了什么?
class view.py
中的声明
class TeamCreate(CreateView): # Manipulate and use this Method instead of create_team
model = Team
# form_class = create_team_form
fields = ['team_name', 'sport', 'sport_season']
success_url = '/'
def get(self, request, *args, **kwargs):
self.user = request.user
print 'happening1'
return super(TeamCreate, self).get(request, *args, **kwargs)
def form_valid(self, form):
print 'happening2'
# form.instance.save()
# self.user.teams.add(form.instance)
form.save()
return super(form_valid, self).form_valid(form)
def form_invalid(self, form):
print "form is invalid"
return http.HttpResponse("form is invalid.. this is just an HttpResponse object")
相关模板代码
{% block content %}
<form action="" method=”POST”>
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" value="Create" />
</form>
看来POST两边的引号根本就不是引号,而是鬼鬼祟祟的忍者断命标记。 “对”。我要睡觉了。
试试这个
<form action="" method="post">
我目前正在使用 django 的 CreateView post 数据到数据库。不幸的是,我想保存和执行自定义逻辑的方法 form_valid() 从未被调用过。我在另一个堆栈溢出响应中读到 form_invalid() 可能会发现问题,但我无法调用该方法。似乎调用的唯一方法是 get(),我覆盖了它并在其中放入了打印语句。我做错了什么?
class view.py
中的声明class TeamCreate(CreateView): # Manipulate and use this Method instead of create_team
model = Team
# form_class = create_team_form
fields = ['team_name', 'sport', 'sport_season']
success_url = '/'
def get(self, request, *args, **kwargs):
self.user = request.user
print 'happening1'
return super(TeamCreate, self).get(request, *args, **kwargs)
def form_valid(self, form):
print 'happening2'
# form.instance.save()
# self.user.teams.add(form.instance)
form.save()
return super(form_valid, self).form_valid(form)
def form_invalid(self, form):
print "form is invalid"
return http.HttpResponse("form is invalid.. this is just an HttpResponse object")
相关模板代码
{% block content %}
<form action="" method=”POST”>
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" value="Create" />
</form>
看来POST两边的引号根本就不是引号,而是鬼鬼祟祟的忍者断命标记。 “对”。我要睡觉了。
试试这个
<form action="" method="post">