我是django的新手,并且一直在努力将User对象传递给ModelForm然后验证它。那就是将User对象作为ForeignKey添加到最后的Note对象中,其中ModelForm是类Note的元。
我的forms.py:
class NoteForm(ModelForm):
class Meta:
model = Note
我的views.py:
def addNote(request):
if request.method == 'POST':
user = User.objects.get(username=request.POST['user'])
model_form = NoteForm(request.POST, request.FILES, user)
if model_form.is_valid():
model_form.save()
return HttpResponseRedirect(reverse('index'))
return HttpResponse('De indtastede data er ikke gyldige')
return render(request, 'studies/uploadfile.html')
我的template.html:
<form enctype="multipart/form-data" method="post" action="/notes/add/">
Note Title: <input type="text" name="name" /> <br />
Select Note: <input type="file" name="note" /> <br />
<input type="hidden" name="user" value="{{ user.id }}">
<input type="submit" value="submit" />
{% csrf_token %}
</form>
我尝试过使用request.user,因为我试图让当前用户登录并将该用户添加为ForreignKey。 任何帮助将不胜感激,事先谢谢。
答案 0 :(得分:7)
我不确定想要将其发送到模板的重点是什么。你在验证之前和之后的视图中都有它:毕竟:更好地处理它。
要做的是从表单定义中排除user
字段,然后在保存时手动设置:
class NoteForm(ModelForm):
class Meta:
model = Note
exclude = ('user',)
if request.method == 'POST':
model_form = NoteForm(request.POST, request.FILES)
if model_form.is_valid():
note = model_form.save(commit=True)
note.user = request.user
note.save()
return...
另请注意,您的视图永远不会向模板发送任何验证错误,并且您的模板不会显示错误或用户输入的无效值。请遵循文档中列出的结构。
答案 1 :(得分:1)
您可以扩展表单的保存方法
def save(self, user):
note = super(NoteForm, self)
note.user = user
note.save()
return note
此外,您的观点必须采用以下结构:
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
# note: NoteForm.save(request.user)
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
答案 2 :(得分:0)