I tried to modify home controller adding new variable:
$data["header_home"] = true;
Then I try to check this in header.twig tetmplate like as:
{% if header_home %}
<div>Home</div>
{% else %}
<div>Not Home</div>
{% endif %}
When I open home page by index.php or just url address it does not work, I mean I dont see <div>Home</div>.
How to fix it, what do wrong?
This is home controller:
<?php
class ControllerCommonHome extends Controller {
public function index() {
$this->document->setTitle($this->config->get('config_meta_title'));
$this->document->setDescription($this->config->get('config_meta_description'));
$this->document->setKeywords($this->config->get('config_meta_keyword'));
if (isset($this->request->get['route'])) {
$this->document->addLink($this->config->get('config_url'), 'canonical');
}
$data["header_home"] = true;
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$this->response->setOutput($this->load->view('common/home', $data));
}
}
Log in to your backend, on your dashboard there will be a settings option.
After you click on it you would see Developer Settings.
Click on Refresh for Theme. Now reload you home page and check if you can see <div>Home</div> .
Related
Our users have the usual CRUD actions in various flask pages.
For one scenario, the Create action can be an intensive process, with lots of domain logic performed, and on occasion, items have been created accidentally.
Our users would now like to add a simple "Are you sure you want to create this Account?" prompt when they click the "Save" button. The next response would simply be Yes and No buttons.
It's not apparent how to add this - are we missing something obvious?
Override the Flask-Admin create template for the particular view and add a JavaScript confirmation to the form's onSubmit event. Adding the confirm to the submit event handles the three submit buttons; 'Save', 'Save and Add Another' and 'Save and Continue'.
For example:
class UserView(ModelView):
create_template = 'create_user.html'
# ...
In the /templates/admin folder add html file 'create_user.html':
{% extends 'admin/model/create.html' %}
{% block tail %}
{{ super() }}
<script src="{{ admin_static.url(filename='admin/js/helpers.js', v='1.0.0') }}" type="text/javascript"></script>
<script>
(function ($) {
$('form:first').on('submit', function() {
return faHelpers.safeConfirm('{{ _gettext('Are you sure you want to save this record?') }}');
});
})(jQuery);
</script>
{% endblock %}
Note there's a bug in Flask-Admin 1.5.3, helpers.js is missing from the distribution and you will need to add the safeConfirm function.
{% extends 'admin/model/create.html' %}
{% block tail %}
{{ super() }}
<script>
(function ($) {
function safeConfirm(msg) {
try {
var isconfirmed = confirm(msg);
if (isconfirmed == true) {
return true;
}
else {
return false;
}
}
catch (err) {
return false;
}
}
$('form:first').on('submit', function () {
return safeConfirm('{{ _gettext('Are you sure you want to save this record?') }}');
});
})(jQuery);
</script>
{% endblock %}
I try to extend my custom User model as described here.
This works fine for the shown fields like ModelChoiceField and CharField.
My goal now is to add a RTF field (the control like the one shown in the Page model). I have looked through the source code of wagtail and found the method get_rich_text_editor_widget which is being used in conjunction with a CharField. Sadly I get a JavaScript error:
Uncaught TypeError: Cannot read property 'initEditor' of undefined
My guess now is that I somehow need to include or modify a hook for the widget. Or is it sufficient to override the JavaScript block in a template? It feels a bit hacky right now and I am stuck with including the required JS, that's why I am posting the question. Maybe I am missing something trivial.
# ...
from wagtail.admin.rich_text import get_rich_text_editor_widget
class CustomUserEditForm(UserEditForm):
position = forms.ModelChoiceField(queryset=Position.objects, required=True, label=_('Position'))
# biography = forms.Textarea()
biography = forms.CharField(widget=get_rich_text_editor_widget())
Update:
Updating my template (maybe not the right approach):
{% block js %}
{{ block.super }}
<script type="text/javascript" src="/static/wagtailadmin/js/draftail.js"></script>
{% endblock js %}
Results in:
I've written my solution up as an issue for draftail
https://github.com/springload/draftail/issues/450
I've got a wagtail site with this awesome RichText Editor (called Draftail) but trying to use it on a non Wagtail Admin page makes me feel dirty. I wanted a biography field that people could write about themselves and I wanted the blog authors to be able to use it as well. BUT to do that I've had to do some things that make me cringe.
Not bad:
{% block extra_css %}
<link href="{% static 'wagtailadmin/css/panels/draftail.css' %}" type="text/css" media="all" rel="stylesheet">
{% endblock extra_css %}
WTF???? why aren't we just using Favicons for things like Bold
<div data-sprite></div>
<script>
function loadIconSprite() {
var spriteURL = '{% url "wagtailadmin_sprite" %}';
var revisionKey = 'wagtail:spriteRevision';
var dataKey = 'wagtail:spriteData';
var isLocalStorage = 'localStorage' in window && typeof window.localStorage !== 'undefined';
var insertIt = function (data) {
var spriteContainer = document.body.querySelector('[data-sprite]');
spriteContainer.innerHTML = data;
}
var insert = function (data) {
if (document.body) {
insertIt(data)
} else {
document.addEventListener('DOMContentLoaded', insertIt.bind(null, data));
}
}
if (isLocalStorage && localStorage.getItem(revisionKey) === spriteURL) {
var data = localStorage.getItem(dataKey);
if (data) {
insert(data);
return true;
}
}
try {
var request = new XMLHttpRequest();
request.open('GET', spriteURL, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
data = request.responseText;
insert(data);
if (isLocalStorage) {
localStorage.setItem(dataKey, data);
localStorage.setItem(revisionKey, spriteURL);
}
}
}
request.send();
} catch (e) {
console.error(e);
}
}
loadIconSprite();
</script>
Because wagtail comments.js somehow needs wagtailConfig.ADMIN_API and draftail won't initialize without comments.js
<script>
(function(document, window) {
window.wagtailConfig = window.wagtailConfig || {};
wagtailConfig.ADMIN_API = {
PAGES: '',
DOCUMENTS: '',
IMAGES: '',
{# // Use this to add an extra query string on all API requests. #}
{# // Example value: '&order=-id' #}
EXTRA_CHILDREN_PARAMETERS: '',
};
{% i18n_enabled as i18n_enabled %}
{% locales as locales %}
wagtailConfig.I18N_ENABLED = {% if i18n_enabled %}true{% else %}false{% endif %};
wagtailConfig.LOCALES = {{ locales|safe }};
wagtailConfig.STRINGS = {% js_translation_strings %};
wagtailConfig.ADMIN_URLS = {
PAGES: ''
};
})(document, window);
</script>
<script src="{% static 'wagtailadmin/js/vendor/jquery-3.5.1.min.js' %}"></script>
<!-- <script src="{% static 'wagtailadmin/js/core.js' %}"></script> strangely not needed -->
<script src="{% static 'wagtailadmin/js/vendor.js' %}"></script>
<script src="{% static 'wagtailadmin/js/comments.js' %}"></script>
{{ form.media.js }}
All of this just to get the draftail editor on a non wagtail admin page!
Which is the best practice to generate in a template a dynamic menu (the menu will be present in all the other app's pages) depending on the user role?
i'm using this in my main template:
{{render(controller('AcmeMainBundle:Sidebar:show'))}}
and this is the controller
class SidebarController extends Controller {
public function showAction() {
$userRole = $this->getUser()->getRoles();
if (in_array("ROLE_ADMIN", $userRole)) {
return $this->render('AcmeMainBundle:Sidebar:sidebarAdmin.html.twig');
} else {
return $this->render('AcmeMainBundle:Sidebar:sidebarUser.html.twig');
}
}
}
but i think it isn't good; what do you think? thanks!
You can achieve this at the view level too. In the template, check the active user's role and hide/show menus depending on the role
{% if is_granted('ROLE_ADMIN') and not is_granted('ROLE_USER') %}
//Show admin stuff
{% else if is_granted('ROLE_USER') %}
//Show user stuff
{% endif %}
If you really want to use the same template for both and not have logic in the template, you can pass parameters to the render method to provide the elements that will be present in your menu.
Been trying for several hours now.
I set up according to instructions but I can't get it to count hits on a blog post.
/blog/blog_post_detail.html
{% load .. .. .. hitcount_tags %}
.
.
.
.
{% block blog_post_detail_content %}
<script type="text/javascript">
$(document).ready(function() {
{% get_hit_count_javascript for blog_post %}
});
</script>
{% get_hit_count for blog_post %}
.
.
.
{% endblock %}
And in my urls.py I added:
url(r'^blog/ajax/hit/$', update_hit_count_ajax, name='hitcount_update_ajax'),
Looking at page source in browser the javascript does appear to run.
$(document).ready(function() {
var csrf = $('input[name=csrfmiddlewaretoken]').val();
$.post( '/blog/ajax/hit/',
{ csrfmiddlewaretoken: csrf, hitcount_pk : '1' },
function(data, status) {
if (data.status == 'error') {
// do something for error?
}
},
'json');
});
But it's not counting. So I'm not quite sure why it doesn't count a page hit.
Figured it out. In Mezzanine you have to put custom url patterns above the
("^", include("mezzanine.urls")),
pattern otherwise they will be ignored.
I want to implement a ajax 'like' button which should increase the like count and not refresh the whole page. I am new to ajax so please help.
urls.py:
(r'^like/(\d+)/$',like),
Below is my views code for like:
def like(request,feedno):
feed=Feed.objects.get(pk=feedno)
t=request.META['REMOTE_ADDR']
feed.add_vote(t,+1)
vote, created = Vote.objects.get_or_create(
feed=feed,
ip=t,
)
feed.likecount+=1
feed.save()
if 'HTTP_REFERER' in request.META:
return HttpResponseRedirect(request.META['HTTP_REFERER'])
return HttpResponseRedirect('/')
Below is my html(like div):
<div class="like_abuse_box">
<p>Likes:<b>{{vote.feed_set.count}}</b> ||
<a class="like" href="/like/{{feed.id}}/">Like</a> |
<a class="abuse" href="/abuse/{{feed.id}}/">Abuse</a> || </p>
</div>
What code should I include to only refresh that particular div and updated like count be shown without the whole page getting reloaded. Need Help. Thanks.
Haven't tested it athough something like that should work. Edit: tested and works, now for multiple elements on a webapage
Javascript
$("a.like").click(function(){
var curr_elem = $(this) ;
$.get($(this).attr('href'), function(data){
var my_div = $(curr_elem).parent().find("b");
my_div.text(my_div.text()*1+1);
});
return false; // prevent loading URL from href
});
Django view
You can add if request is Ajax with:
if request.is_ajax():
First thing: put an id on the html element where the content to be injected.
<div class="like_abuse_box">
<p>Likes:<b id="like_count">{{vote.feed_set.count}}</b> ||
<a class="like" href="/like/{{feed.id}}/">Like</a> |
<a class="abuse" href="/abuse/{{feed.id}}/">Abuse</a> || </p>
</div>
second, in your view you need to return the latest like count. You can't just locally update the count, since there is a chance that someone else may have updated the like count as well.
Lastly. in your page include the jquery
$("a.like").bind("click", function(){
var link = $(this).attr("href");
$.get(link, function(data) {
$(this).parent("div").children('b#like_count').html(data);
});
});
I am not quite certain about the parent child selector, to navigate from hyper linked clicked to its corresponding like count. You may have to play around with JQuery selector to get it right.
ALso, if you are using POST for your view, replace $.get with $.post