如何让Django的通用视图使用具有初始值的窗体? [英] How to let Django's generic view use a form with initial values?
问题描述
我知道如何从视图中将初始值设置为窗体。但是,如何让一般的视图将初始值设置为一个窗体呢?我可以为通用视图写一个包装器视图,但是我仍然无法访问表单对象实例化。
我要实现的具体目标是拥有用户使用create_object泛型视图创建新对象。但是,我想将对象user的字段设置为当前登录的用户,该用户只能以request.user方式访问。如何将表单初始化为具有此字段?
编辑:我遇到__new__。可以使用一些默认参数调用自己的构造函数吗?
非常感谢。
不幸的是,您不能通过Django的 create_object
通用视图来实现此行为。你必须自己写。但是,这很简单。
要开始,您必须创建一个新的表单类,如下所示:
从django import forms
class MyForm(forms.ModelForm):
class Meta:
model = MyModel#model有一个用户字段
然后你可以创建一个这样的视图:
从django.shortcuts导入render_to_response
从django.template导入RequestContext
从django.http导入HttpResponseRedirect
从django.contrib.auth.decorators import login_required
@login_required
def create_mymodel(request):
如果request.method =='POST':
#从表单
获取数据= MyForm(request.POST)
#如果表单有效,请创建一个新对象并重定向到该对象。
如果form.is_valid():
newObject = form.save()
返回HttpResponseRedirect(newObject.get_absolute_url())
else:
#填写字段与当前用户默认
form = MyForm(initial = {'user':request.user})
#渲染我们的模板
返回render_to_response('path / to / template.html' ,
{'form':form},
context_instance = RequestContext(request))
I know how to set initial values to a form from the view. But how do I go about letting a generic view set initial values to a form? I can write a wrapper view for the generic view, but I still have no access to the form object instantiation.
The specific goal I'm trying to achieve is to have a user create a new object, using the create_object generic view. However, I'd like to set a field of the object 'user' to the currently logged in user, which is only accessible as request.user. How can the form be initialized to have this field?
Edit: I came across __new__. Could this call its own constructor with some default arguments?
Many thanks.
Unfortunately, you cannot achieve this behavior through Django's create_object
generic view; you will have to write your own. However, this is rather simple.
To start off, you must create a new form class, like this:
from django import forms
class MyForm(forms.ModelForm):
class Meta:
model = MyModel # model has a user field
Then you would be able to create a view like this:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required
def create_mymodel(request):
if request.method == 'POST':
# Get data from form
form = MyForm(request.POST)
# If the form is valid, create a new object and redirect to it.
if form.is_valid():
newObject = form.save()
return HttpResponseRedirect(newObject.get_absolute_url())
else:
# Fill in the field with the current user by default
form = MyForm(initial={'user': request.user})
# Render our template
return render_to_response('path/to/template.html',
{'form': form},
context_instance=RequestContext(request))
这篇关于如何让Django的通用视图使用具有初始值的窗体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!