本文介绍了扩展Django的通用视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在Django中编写我的第一个应用程序,而且我有一个问题: create_object Generic View;在我的 urls.py 中,我有: (r'^新$',CreateView.as_view()), 问题是当用户提交新的表单,我需要操纵将被保存到数据库的数据(我实际上需要添加 user_id 外键);没有通用意见我曾经写过: form = ClientForm(request.POST)如果form.is_valid() : data = form.save(commit = False) data.user = request.user data.save() form.save_m2m() 在我的视图(通知 data.user = request.user )。我已经搜索过Django文档,但是找不到这样做的方式(也许通过扩展 CreateView 类) - 在本书中,只有一个覆盖的例子一个 ListView 类的 get_object 方法来更新 last_accessed_date 解决方案您可以通过覆盖 get_form 方法来执行此操作:导入CreateView class CustomCreateView(CreateView) def get_form(self,form_class): form = super(CustomCreateView,self).get_form(form_class) form.instance.user = self.request.user return form 编辑:现在我将覆盖 form_valid 根据 Issac Kelly的回答: from django.views.generic import CreateView class CustomCreateView(CreateView): def form_valid(self,form): form.instance.user = self.request.user return super(CustomCreateView,self).form_valid (形式) I'm writing my first app in Django, and I have a problem with the create_object Generic View; In my urls.py, I have:(r'^new$', CreateView.as_view()),The problem is that when the user submits the "new" form, I need to manipulate the data that will be saved to the database (I actually need to add the user_id foreign key); without Generic Views I used to write: form = ClientForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() form.save_m2m()in my view (notice data.user=request.user). I've searched Django docs but I can't find a way to do this (maybe by extending the CreateView class) - somewere in The Book there is only an example that overrides the get_object method of a ListView class to update a last_accessed_date field. 解决方案 You can do this by overriding the get_form method:from django.views.generic import CreateViewclass CustomCreateView(CreateView): def get_form(self, form_class): form = super(CustomCreateView, self).get_form(form_class) form.instance.user = self.request.user return formEDIT: Nowadays I would override form_valid as per Issac Kelly's answer:from django.views.generic import CreateViewclass CustomCreateView(CreateView): def form_valid(self, form): form.instance.user = self.request.user return super(CustomCreateView, self).form_valid(form) 这篇关于扩展Django的通用视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-15 08:06