我尝试了3种不同的方法,似乎没有任何效果。这是我的观点:
def my_view(request):
if request.method == 'POST':
form = DealershipForm(request.POST)
if form.is_valid():
dealership = form.save(commit=False)
dealership.entered_by = User(id=2)
dealership.save()
messages.success(request, 'Dealership added.')
else:
form = DealershipForm()
return response(request, template='misc/my_template.html',
vars={'form':form})
我也尝试在cleaned_data
之后修改form.is_valid
,我尝试设置initial
和instance
,似乎没有任何效果!
答案 0 :(得分:4)
DealershipForm(request.POST, instance=Dealership(my_field="my_value"))
应该工作。
修改强>
修改后的代码:
def my_view(request):
if request.method == 'POST':
form = DealershipForm(request.POST, instance=Dealership(entred_by=User(id=2))
if form.is_valid():
form.save()
messages.success(request, 'Dealership added.')
else:
form = DealershipForm()
return response(request, template='misc/my_template.html',
vars={'form':form})
在评论后修改:
def my_view(request):
if request.method == 'POST':
instance = Dealership()
instance.entered_by_id = 2
form = DealershipForm(request.POST, instance=instance)
if form.is_valid():
form.save()
messages.success(request, 'Dealership added.')
else:
form = DealershipForm()
return response(request, template='misc/my_template.html',
vars={'form':form})