我正在尝试使用Django的消息框架。
我完全按照https://docs.djangoproject.com/en/dev/ref/contrib/messages/#enabling-messages
的说法完成了我按messages.success(self.request, 'Updated.')
添加消息,但不显示任何消息。 {% if messages %}
一如既往地评估错误。
如果我打印{{ messages }}
,我会<django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fb701c47b70>
。
有什么不对?
我的中间件
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
我的模板上下文处理器
TEMPLATE_CONTEXT_PROCESSORS = [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.core.context_processors.request",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages"
]
我已安装的应用
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
)
class ItemUpdateView(LoginRequiredMixin, UpdateView):
model = Item
context_object_name = 'item'
form_class = ItemForm
def get_form_kwargs(self):
kwargs = super(ItemUpdateView, self).get_form_kwargs()
kwargs["user"] = self.request.user
return kwargs
def form_valid(self, form):
with transaction.atomic(), reversion.create_revision():
self.object = form.save()
reversion.set_user(self.request.user)
reversion.set_comment("Updating")
messages.success(self.request, "Updated")
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return self.object.get_update_url()
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% else %}
no messages
{% endif %}
这对我来说是一个很大的谜。
如果我使用
,则不会添加消息def form_valid(self, form):
self.object = form.save()
messages.success(self.request, "Updated")
return HttpResponseRedirect(self.get_success_url())
但如果我使用
,它会添加消息def dispatch(self, request, *args, **kwargs):
messages.success(request, 'Updated.')
return super(ItemUpdateView, self).dispatch(request, *args, **kwargs)
答案 0 :(得分:0)
发布此信息以帮助未来用户。
要解决此问题,您必须在form_valid函数中添加对super()的调用:
<?php
define("ROW_PER_PAGE",1);
$search = '';
if (!empty($_POST['search'])) {
$search = $_POST['search'];
/* Search Entry */
$keywords = explode(' ', $search);
$arr_length = count($keywords);
$sub_query = '';
for ($i = 0; $i < $arr_length; $i++) {
if ($i == 0) {
$sub_query = $sub_query . 'sym_body LIKE "%' . $keywords[$i] . '%" OR sym_tags LIKE "%' . $keywords[$i] . '%"';
}else {
$sub_query = $sub_query . ' OR sym_body LIKE "%' . $keywords[$i] . '%" OR sym_tags LIKE "%' . $keywords[$i] . '%"';
}
}
/* Query */
$query = 'SELECT * FROM symptoms WHERE ' . $sub_query;
/*Pagination Code Starts */
$per_page_htm = '';
$page = 1;
$start = 0;
if(!empty($_GET['r'])) {
$page = $_GET['r'];
$start = ($page - 1) * ROW_PER_PAGE;
}
$limit = "LIMIT " . $start . "," . ROW_PER_PAGE;
/* Getting Row Count Tested Working */
$p_query = 'SELECT COUNT(*) FROM symptoms WHERE ' . $sub_query;
$pag_stnt = $con->query($p_query);
$row_count = $pag_stnt->fetchColumn();
echo "<h4>You have $row_count result(s)</h4>";
if (!empty($row_count)) {
$per_page_htm .= "<div style='text-align:center;margin:20px 0px;'>";
$page_count = ceil($row_count / ROW_PER_PAGE);
if ($page_count > 1) {
$self = $_SERVER['PHP_SELF'];
for($i=1; $i<=$page_count; $i++){
if($i==$page){
$per_page_htm .= "<a href='".$self."?r=".$i."' class='btn-page current'>".$i."</a>";
}else{
$per_page_htm .= "<a href='".$self."?r=".$i."' class='btn-page'>".$i."</a>";
}
}
}
$per_page_htm .= "</div>";
$n_query = 'SELECT * FROM symptoms WHERE ' . $sub_query . ' '.$limit ;
foreach ($con->query($n_query) as $row) {
$sym_cat_id = $row['cat_id'];
$sym_pro = $row['sym_pro'];
$sym_body = $row['sym_body'];
$sym_ans = $row['sym_answer'];
?>
<!-- Symptom Area-->
<div class="panel-group results">
<div class="panel panel-success">
<div class="panel-heading">
<p><?php //echo $cat_title;?></p>
<?php echo $search; ?>
</div>
<div class="panel-body">
<?php echo $sym_body; ?>
<p><h4>Answer</h4>
<?php echo $sym_ans;?></p>
<p><h4>Was the answer helpful</h4></p>
<p>
<a href="index.php" class="btn btn-info pull-left"> Yes</a>
<button type="button" class="btn btn-danger pull-right">No</button>
</p>
</div>
</div>
</div>
<?php
}
}else{
echo '<script>
setTimeout(function(){
swal({
title: "Sorry!",
text: "Your Query is not in our database",
type: "info"
}, function(){
window.location = "index.php";
});
}, 1000);
</script>';}
echo $per_page_htm;
}else{
echo '<script>
setTimeout(function(){
swal({
title: "Oops!",
text: "Please enter a valid value!",
type: "error"
}, function(){
window.location = "index.php";
});
}, 1000);
</script>';} ?>
答案 1 :(得分:-1)
您没有在模板中看到您的消息,因为form_valid返回一个HttpResponse,它会将请求对象丢弃在地板上。
请注意您的解决方案 如何向前传递请求对象。
return super(ItemUpdateView, self).dispatch(request, *args, **kwargs)
你可以做些什么来确保你总是在视图中获取消息并将其作为上下文对象传递。那么响应方法就不重要了。
from django.contrib import messages
class Homepage(View):
template_name = 'index.html'
def get(request):
return render(request, self.template_name, {
'messages': messages.get_messages(request)
})
def post(request):
return HttpResponseRedirect('/home/')