我尝试了许多选择,但没有一个起作用。我想用登录用户作为初始数据来初始化表单。
#My form
class AdaugaPorumbel(forms.ModelForm):
class Meta:
model = Porumbei
fields = ['data_adaugare', 'crescator', 'serie_inel', 'anul', 'culoare', 'culoare_ochi', 'sex', 'ecloziune',
'rasa', 'linie', 'nume', 'tata',
'mama', 'compartiment', 'status', 'data', 'vaccinat', 'info', 'imagine', 'imagine_ochi']
widgets = {
'ecloziune': forms.DateInput(format='%d/%m/%Y',
attrs={'class': 'form-control', 'type': 'date'}),
'data': forms.DateInput(format='%d/%m/%Y',
attrs={'class': 'form-control', 'type': 'date'}),
'vaccinat': forms.DateInput(format='%d/%m/%Y',
attrs={'class': 'form-control', 'type': 'date'}),
'info': forms.Textarea(attrs={'class': 'form-control mt-15', 'rows': '3',
'placeholder': 'Vor apărea în pedigree'}),
}
# My view
@login_required(login_url='/auth/login/')
def porumbelnou(request):
if request.method == "POST":
form = AdaugaPorumbel(request.POST, request.FILES, initial={'crescator': crescator})
if form.is_valid():
form.save()
return HttpResponseRedirect('/porumbei/vizualizare')
else:
form = AdaugaPorumbel()
context = {
'form': form,
}
template = loader.get_template("adaugare-porumbel.html")
return HttpResponse(template.render(context, request))
# I've already try but still won't working
if form.is_valid:
form.save(commit=False)
form.crescator = request.user
form.save()
...
在模型上,crescator字段是设置为settings.AUTH_USER_MODEL的外键。
答案 0 :(得分:0)
从表单字段中删除crescator
。然后在表单验证之后,将用户分配给对象
form = AdaugaPorumbel(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
obj.crescator = request.user
obj.save()