如何将 Django 消息写入您的视图代码
How to write a Django message into your views code
我正在阅读有关如何使用 Django 消息向用户显示消息的文档。它说为了在您的视图中添加一条消息来调用:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
我不确定第二行放在哪里,这是我的看法:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
return HttpResponse('Thank you')
else:
return HttpResponse('That text is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
我希望消息显示并感谢用户注册并显示他们的输入。
请记住,在提交有效表单时重定向到成功 url 是惯例,您的代码应如下所示:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
messages.add_message(request, messages.INFO, 'Hello world.')
return HttpResponseRedirect('/thank-you-page/')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
请注意,这也会导致用户被告知其表单无效的确切原因(假设您已正确设置模板)。说问题是什么总比说有问题好。
您可以将第二行放在视图中,例如:
def contact(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
textarea = request.POST.get('textarea')
contact = Contact(name = name,email = email,password = password,textarea = textarea,date=datetime.today())
contact.save()
messages.success(request, 'Form has submitted')
return render(request,"contact.html")
我正在阅读有关如何使用 Django 消息向用户显示消息的文档。它说为了在您的视图中添加一条消息来调用:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
我不确定第二行放在哪里,这是我的看法:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
return HttpResponse('Thank you')
else:
return HttpResponse('That text is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
我希望消息显示并感谢用户注册并显示他们的输入。
请记住,在提交有效表单时重定向到成功 url 是惯例,您的代码应如下所示:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
messages.add_message(request, messages.INFO, 'Hello world.')
return HttpResponseRedirect('/thank-you-page/')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
请注意,这也会导致用户被告知其表单无效的确切原因(假设您已正确设置模板)。说问题是什么总比说有问题好。
您可以将第二行放在视图中,例如:
def contact(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
textarea = request.POST.get('textarea')
contact = Contact(name = name,email = email,password = password,textarea = textarea,date=datetime.today())
contact.save()
messages.success(request, 'Form has submitted')
return render(request,"contact.html")