我知道如何从视图中为表单设置初始值。但是,如何让通用视图将初始值设置为表单?我可以为通用视图编写包装器视图,但我仍然无法访问表单对象实例化。
我想要实现的具体目标是让用户使用create_object泛型视图创建一个新对象。但是,我想将对象'user'的字段设置为当前登录的用户,该用户只能以request.user身份访问。如何将表单初始化为具有此字段?
编辑:我遇到了__new__。这可以用一些默认参数调用它自己的构造函数吗?
非常感谢。
答案 0 :(得分:4)
不幸的是,您无法通过Django的create_object
通用视图实现此行为;你必须自己写。但是,这很简单。
首先,您必须创建一个新的表单类,如下所示:
from django import forms
class MyForm(forms.ModelForm):
class Meta:
model = MyModel # model has a user field
然后你就可以创建一个这样的视图:
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))
答案 1 :(得分:3)
您可以通过动态构建表单类并将其传递给通用视图,在通用视图包装器中执行此操作,但这种治疗方法可能比疾病更糟糕。只需编写自己的视图,然后急切等待this降落。
答案 2 :(得分:0)
如果您想要通用视图的所有功能,那么您可以使用原始模板创建新的通用视图。
例如:
def create_object_with_initial(request, model=None, template_name=None,
template_loader=loader, extra_context=None, post_save_redirect=None,
login_required=False, context_processors=None, form_class=None, initial=None):
if extra_context is None: extra_context = {}
if login_required and not request.user.is_authenticated():
return redirect_to_login(request.path)
model, form_class = get_model_and_form_class(model, form_class)
if request.method == 'POST':
form = form_class(request.POST, request.FILES)
if form.is_valid():
new_object = form.save()
msg = ugettext("The %(verbose_name)s was created successfully.") %\
{"verbose_name": model._meta.verbose_name}
messages.success(request, msg, fail_silently=True)
return redirect(post_save_redirect, new_object)
else:
print "creating", form_class, " with initial data ", initial
form = form_class(initial=initial)
# Create the template, context, response
if not template_name:
template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())
t = template_loader.get_template(template_name)
c = RequestContext(request, {
'form': form,
}, context_processors)
apply_extra_context(extra_context, c)
return HttpResponse(t.render(c))
这是从/site-packages/django/views/generic/create_update.py复制的,只有第3行和第21行更改为包含初始数据。
然后按照您的预期使用它:
object_info = {
'model': YourModel,
'initial': {'data' : 'Initial Value'},
'template_name': 'template.html'
}
url(r'^path/$',
login_required(create_object_with_initial),
object_info,
name='url_name'),
这应该有效。