我正在尝试将功能视图转换为类视图。函数视图完美无缺,但我似乎无法通过form_view的form_valid函数。
以下是基于功能的视图:
@login_required
def add_friends(request, tab_name_slug):
# twitter friends into a list
friends = [u.screen_name for u in tweepy.Cursor(api.friends).items()]
tabs = get_or_none(Tab, user=request.user, slug=tab_name_slug)
user_tab = get_or_none(FriendsList, user=request.user, tab=tabs)
tab_friends = ast.literal_eval((user_tab.flist).decode()) if user_tab != None else None
# friendlist form
if request.method == 'POST':
form = FriendsListForm(request.POST)
if form.is_valid():
# Delete existing list
if user_tab != None:
user_tab.delete()
flist = form.save(commit=False)
flist.tab = tabs
flist.user = request.user
flist.save()
# New Added Friends into Category
tabs = get_or_none(Tab, user=request.user, slug=tab_name_slug)
user_tab = get_or_none(FriendsList, user=request.user, tab=tabs)
tab_friends = ast.literal_eval((user_tab.flist).decode()) if user_tab != None else None
# delete friends that aren't in the friend category list
[friend.delete() for friend in Friend.objects.filter(friend=request.user, tab=tabs)]
[Friend.objects.create(friend=request.user, tab=tabs, name= new_friend) for new_friend in tab_friends]
else:
print form.errors
else:
form = FriendsListForm()
context_dict = {'form':form, 'tabs': tabs, 'friends': friends, 'tab_friends': tab_friends}
return render(request, 'ttapp/add_friends.html', context_dict)
以下是基于类的视图:
class AddFriendsView(FormView, LoginRequiredMixin):
template_name = "ttapp/add_friends.html"
form_class = FriendsListForm
success_url = '/home/'
def get_context_data(self, *args, **kwargs):
context = super(AddFriendsView, self).get_context_data(*args, **kwargs)
friends = [u.screen_name for u in tweepy.Cursor(api.friends).items()]
tabs = get_or_none(Tab, user=self.request.user, slug=self.kwargs["tab_name_slug"])
user_tab = get_or_none(FriendsList, user=self.request.user, tab=tabs)
tab_friends = ast.literal_eval((user_tab.flist).decode()) if user_tab != None else None
context = {'tabs':tabs, 'friends':friends, 'tab_friends': tab_friends}
return context
def form_valid(self, form):
print "valid"
return super(AddFriendsView, self).form_valid(form)
def form_invalid(self, form):
print "invalid"
return self.render_to_response(self.get_context_data(form=form))
编辑:
找出类视图没有显示像在函数视图中那样的字段(使用{{form.as_p}}从django表单自动生成)。
就是这样:
<textarea cols="40" id="id_flist" name="flist" rows="10" style="display: none;"></textarea>