Django - 如何将用户对象传递到views.py中的表单
我是django的新手,并且已经绑定将User对象传递给ModelForm,然后验证它。最后,将User对象作为ForeignKey添加到Note对象,其中ModelForm是类Note的Meta。Django - 如何将用户对象传递到views.py中的表单
我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。 任何帮助将不胜感激,事先感谢。这里https://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext
回答:
回答:
看我不知道该点是想将其发送到模板的东西。毕竟,在验证之前和验证之后,您都可以在视图中看到它:更好地在那里处理它。
要做的事情是从表单定义排除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...
另外请注意,您的观点永远不会发送任何验证错误的模板,模板不显示错误或用户输入的无效值。请遵循文档中列出的结构。
回答:
可以延长保存表单的方法,
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,
})
(从https://docs.djangoproject.com/en/dev/topics/forms/复制)
以上是 Django - 如何将用户对象传递到views.py中的表单 的全部内容, 来源链接: utcz.com/qa/265900.html