我有一个django应用程序,它有一些中间件(以新样式编写),用于检查用户是否可以注册的内容在用户完成注册之前变为“满”。
如果它已经满了 - 中间件启动一条错误消息,让用户知道它已满,并将它们链接到他们的注册,以便他们可以更改它。
中间件看起来像这样:
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
# ....extra logic (working without issue)....
full_problem_registrations = Registration.objects.filter(
id__in=full_problem_registration_ids
)
request.full_problem_registrations = full_problem_registrations
request.session['registration_now_full'] = False
if full_problem_registrations:
request.session['registration_now_full'] = True
for problem_reg in full_problem_registrations:
reg_url = reverse(
"camp_registrations:edit_registration", kwargs={
'person_id': problem_reg.person.id,
'registration_id': problem_reg.id,
}
)
url_string = '<a href="%s">' % reg_url
error_message = format_html(
"The %s %s registration for %s %s at %s</a> has become\
full and is no longer available. Please either remove\
or change this registration." % (
url_string,
problem_reg.course_detail.course.camp.name,
problem_reg.person.first_name,
problem_reg.person.last_name,
problem_reg.course_detail.location.name,
)
)
existing_messages = get_messages(request)
if existing_messages:
for message in get_messages(request):
# check for duplicates
if message.message == error_message:
pass
else:
messages.error(
request,
error_message,
)
else:
messages.error(
request,
error_message,
)
else:
pass
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
这很有效 - 显示的消息让每个人都知道用户注册时遇到问题。
但是 - 当用户进入编辑注册并更改为非完整课程并保存时 - 当他们保存时,会将其重定向到下一页。
在下一页显示成功消息 - 但也会继续显示错误消息。如果用户刷新或转到站点上的任何其他页面,则错误消息将消失。
这是因为中间件在处理视图之前正在处理 - 并且此时错误仍然存在。
解决这个问题并避免显示的最佳方法是什么?
在处理视图后我想到了中间件部分(我相信这将包括处理POST数据)然后我们可以再次运行检查并删除错误(如果存在);但我无法弄清楚如何很好地从消息中删除错误。
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
# should I be checking here to see if the problem still exists and
# removing the message here?
我已经尝试过 - 但是要弄清楚如何从FallbackStorage
对象中删除那个特定的消息。
使用基于类的视图处理表单(特别是这个是UpdateView
)
因为你似乎继续对每个请求运行检查,并且据我所知,“问题”消息不断干扰其他人(如“成功”消息)并且很难区分它们我会建议可能不使用消息框架为此,你可以例如。只需创建一个简单的context processor,它可以为每个请求的每个模板提供完整注册的数据。因此,这些消息不会持久保存到会话中,而是在每个请求上新生成。
就像是:
# context processor
def registrations(request):
# .....
full_problem_registrations = Registration.objects.filter(
id__in=full_problem_registration_ids
)
return full_problem_registrations
# add a snippet to eg. your base template
{% if full_problem_registrations.exists %}
Generate problem messages here
{% endif %}