I want to pass data from models to template using CMS_plugins.py
I've made an app and standalone works. When i open link manualy
localhost:port/en/post_list.html all values are shown and works.
If i go on admin page and add plugin, values in mysql are stored but not presended in my template.html . I want to pass values in template.html
EDIT:
I manage to pass values to template. I edited cms_plugins.py
How can i hook data with "for" ?.
In code blow, nothing isnt shown in my template.html
<p>{{instance.firstline}}</p> ->>>this works
{ %block content %}
{{ instance.post.offer_option}}
<p>{{post.firstline}}</p>
<p>{{post.secline}}</p>
{% endfor %}
{% endblock}
if i change to :
{% for post in posts %}
<p>{{post.firstline}}</p>
<p>{{post.secline}}</p>
{% endfor %}
{% endblock}
In upper case if i run manualy url: localhost:port/en/pricing , I can see the result i want to be rendered in template.In template nothing isnt shown neither.
cms_plugins.py
class pricing(CMSPluginBase):
model = Post
name = _("pricing")
render_template = "post_list.html"
cache = False
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
plugin_pool.register_plugin(pricing)
Related
I want to loop data taken from database in rendered template. Using cms plugin.
I dont have problem looping data in html template. But if i use CMSPlugin to insert new app in placeholder, nothing shows.
If i run url localhost:port/test.html.I got input what i want. But rendered template doesnt loop data.
{% for post in posts %}
{{ post.firstoption }}
{% endfor %}
if I use code below, nothing shows in my rendered template. Values are passed in rendered template. Because, if i try {{instance.firstoption}} i get value shown in template. Problem is i cant loop data with tag instance.
{% for post in instance.posts %}
{{ post.firstoption }}
{% endfor %}
I also tried {% for post in instance.posts_set.all %}
and {% for post in instance.posts.all %}
cms_plugins.py
class pricing(CMSPluginBase):
model = mymodel
name = _("myplugin")
render_template = "template.html"
cache = False
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
models.py
class mymodel(CMSPlugin):
firstoption = models.CharField(max_length=200)
def __str__(self):
return self.firstoption
It is probably because you need to call all on your posts
{% for post in instance.posts.all %}
{{ post.firstoption }}
{% endfor }
I want to try and show or hide urls in my navigation page based on user group.
currently i am adding to the top of every view and sending through a value to the template and checking against that, but this doesnt seem too efficient, also if a view does not require auth and that value is not set, will that break the template?
is there a better way to do this?
like a global.py where i could check and set then use it in any template? or something completely different altogether?
view.py
Authorised_user = ''
if request.user.is_authenticated():
Authorised_user = 'IT'
#login_required
def index(request):
return render(request, 'service/index.html', {
'Authorised': Authorised_user,
})
template.html
{% if Authorised == 'IT' or Authorised =='Netwworks' %}
Link
{% endif %}
i do have the user groups in django admin
Based on Get user group in a template
Create user_tags.py / group_tags.py at an appropriate place. e.g. auth_extra/templatetags/user_tags.py
from django import template
register = template.Library()
#register.filter('in_group')
def in_group(user, group_name):
return user.groups.filter(name=group_name).exists()
Then in your template:
{% load user_tags %}
{% if request.user|in_group:"IT"%}
IT only link
{% endif %}
{% if request.user|in_group:"Netwworks"%}
Netwworks only link
{% endif %}
Easiest way around this for me was https://stackoverflow.com/a/17087532/8326187.
Here you don't have to create a custom template tag.
{% if request.user.groups.all.0.name == "groupname" %}
...
{% endif %}
You need to create context_processors.py and create a function say
def foo():
Authorised_user = ''
if request.user.is_authenticated():
Authorised_user = 'IT'
Then in setttings
TEMPLATE_CONTEXT_PROCESSORS = ("path_to_context_processor.foo")
this way you can use foo variable in all the templates without explicitly defining in all the views.
You can also have a look here:https://rubayeet.wordpress.com/2009/10/31/django-how-to-make-a-variable-available-in-all-templates/
I'm trying to create a custom placeholder to add an admin-editable section on a website. Django-cms' documentation is really generic about what's to be done to add it.
The placeholder lives in a separate app, called contacts, already added to the settings.py file
Here's my code up to now (skipping imports to be less verbose):
models.py
class ContactsPlaceholder(models.Model):
phone = models.CharField(max_length=100)
email = models.CharField(max_length=100)
address = models.TextField(max_length=700)
# your fields
my_placeholder = PlaceholderField('contacts_contactsplaceholder')
# your methods
def __unicode__(self):
return "Contacts Placeholder"
views.py
def contacts(request):
# Load the the contacts from db
contactsfields = ContactsField.objects.all()
contacts_placeholder = ContactsPlaceholder.objects.all()
context = {"contactsfields" : contactsfields, "contacts_placeholder" : contacts_placeholder}
return render(request, "../templates/contacts.html", context)
def contacts_placeholder_detail(request, id): # is this really useful?
object = get_object_or_404(ContactsPlaceholder, id=id)
return render_to_response('../templates/contacts_placeholder_detail.html', {
'object': object,
}, context_instance=RequestContext(request))
contacts.html
{% extends "base.html" %}
{% load cms_tags %}
{% block content %}
<div>
<h1>Contacts</h1>
{% placeholder "contacts_placeholder" or %}
<p>Placeholder is empty</p>
{% endplaceholder %}
</div>
{% endblock content %}
and finally, admin.py
class ContactsPlaceholderAdmin(PlaceholderAdminMixin, admin.ModelAdmin):
# Editable fields
frontend_editable_fields = ("phone", "email", "address")
# Form fields order and sections
fieldsets = [
(None,{"fields" : ["phone", "email", "address"]})
]
admin.site.register(ContactsPlaceholder, ContactsPlaceholderAdmin)
With this configuration, after having run python manage.py syncdb I do get "Placeholder is empty" in the html response, and of course the placeholder is not editable using the standard frontend editor, which was the desired behaviour.
Going to 127.0.0.1:8000/admin/ i can see the "Contacts Placeholder" table, however when I click it or try to add items I do get the following error:
OperationalError at /us/admin/contacts/contactsplaceholder/
no such column: contacts_contactsplaceholder.phone
If the contacts() view is rendered via an app hook then using {% placeholder "contacts_placeholder" %} in the template won't work.
When using Placeholders in apps connected to the CMS via an AppHook you must use {% static_placeholder "MyPlaceholder" %} instead of the usual {% Placeholder "MyPlaceholder" %}
If you've got an app or a plugin in which you've created a PlaceholderField, then in your template which renders that, you'd need the following tag;
{% render_placeholder instance.placeholderfieldname %}
I'm trying to build a website that has products and categories.
When you are on the page of a product, you can click a button to see a list of all the categories it falls under.
You can click another button, that appears on all pages, to see a list of all the categories overall.
In the html page see_all_categories, I wrote a simple block like this:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content%}
{{Category.all}}
{% endblock content %}
I expect to see a messy printout of all the categories but I don't. It doesn't return an error, but it produces nothing, other than the base.html.
What am I doing wrong?
You want to display a list of the categories. I assume your Category model owns an attribute named "title" which is the representation of your Category.
If you're using Django template engine or Jinja2, you can make a for loop inside your template like this :
{% for cat in Category.objects.all %}
{{ cat.title }}
{% endfor %}
As a troubleshooting, I'd suggest you didn't pass your Category model to your template, that is not done automatically. You have to add your model to the context before rendering the template.
As mentionned in the comments, here is doc for template rendering with Django templates.
Django Template Guide
To add your model to the context you can follow this guide.
I don't intend to help you further because I lack of information and that may vary a LOT according to your settings. (Class Based views ? Function based views ? What kind of template are you using... And so on)
I figured out the solution after many long annoying hours of trying everything. I feel dumb but I want to spare the next guy the massive pain in the two-pack.
This is what I did:
In the Views.py, I changed the view function for this page FROM this:
def view_all_categories(request):
context = {'Category' : Category}
return render(request, 'store/see_all_categories.html', context)
TO this
def view_all_categories(request):
all_cats = Category.objects.all().order_by('id')
context = {'all_categories' : all_cats}
return render(request, 'store/see_all_categories.html', context)
and in the page see_all_categories.html itself, I changed it (from the question) TO this:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content%}
{% for cat in all_categories %}
<p>{{ cat.name }}</p>
{% endfor %}
{% endblock content %}
And now it works!!
I've been working with Django in order to make my portfolio and I've managed to make a simple page manager. The problem is, it does not work how I want it to work:
I create the page.
It loads the content I gave it.
With jQuery, I load only that content (as formatted HTML).
It shows itself without reloading or moving to another page.
The problem is with the last two steps, I can't get the view and template to only load one.
Views.py:
def paginas(request, title):
get_page = Page.objects.all() # I can't think of a way to make a proper filter
return render_to_response('template.html', {'get_page': get_page}, context_instance=RequestContext(request), mimetype="text/html")
Template.html:
{% if get_page %}
{% for page in get_page %}
{{ page.content|safe }}
<p>Full path is {{ request.get_full_path }} and page id is {{ page.id }}</p>
{% endfor %}
{% else %}
<p>Nothing.</p>
{% endif %}
I know I should filter it, but I don't know how.
I appreciate your help.
tbh, the django tutorial explains urls, parameters and forms very clear, but here's the idea:
url(r'^/someapp/(?P<page_id>\d+)/$', paginas),
def paginas(request, **kwargs):
id = kwargs.pop('page_id')
page = get_object_or_404(Page, id=id)
# etcetera
class Page(models.Model):
# regular stuff
def get_absolute_url(self):
return "/someapp/%d/" % self.id
In paginas you are obviously getting all Pages.
To get one page you can use the get function
def paginas(request, title):
try:
your_page = Page.objects.get(title=title)
except Page.DoesNotExist:
# error no page for that title
# could use built in get_object_or_404 as ArgsKwargs suggested
It's also important to consider using a slug to make sure encoding is correct. The page id would be even better to use