i am a new to Django, i am trying to make a small blog with two different languages, i got all the translations inside my blog including the admin, but still don't know how to translate the content of my posts.
After i fetch the content using the models queries, inside my template i used to type this {% trans "SOME TEXT" %} and it works just fine, with variables that i am getting from database i am using this code:
{% blocktrans %}
{{head.title_text}}
{% endblocktrans %}
now when i type django-admin makemessages -l ru, inside django.po i can't see any new text that have been added.
Also inside my views.py i tried this:
head = Head.objects.first()
trans_h = _(u'{}'.format(head))
but nothing gets added inside django.po
Please, anyone knows how to resolve this issue ??
I think the best way to translate the content of the Post Model without using any third-party is to create for each fields you need to translate inside your models with different languages and translate them from your admin,and display them in your template when the site change the language, in Django you can translate only the text you can not translate the data from your model
Create your model Post
models.py
class Post(models.Model)
title_fr = models.CharField(max_length=200)
title_en = models.CharField(max_length=200)
content_fr = models.TextField()
content_en = models.TextField()
created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
In the view you translate the text inside the variable and pass it in your template
views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .models import Post
from django.utils.translation import ugettext_lazy as _
def post_view(request):
post = Post.objects.all()
# Here is you can translate the text in python
title = _("les meilleurs posts du mois")
context = {
'post':post,
'title':title
}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Here the idea is once your site is translated in french for example(www.mysite.com/fr/) in your template you will get only the attributes with _fr(title_fr, content_fr) already translated in your admin and if it's in english it will be the same thing
index.html
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_available_languages as LANGUAGES %}
<h1> {{ title}}</h1>
{% if LANGUAGE_CODE|language_name_translated == 'Français' %}
{% for items in home %}
<h2>{{ items.title_fr }}</h2>
<p> {{items.content_fr}}</p>
{% endfor %}
{% if LANGUAGE_CODE|language_name_translated == 'English' %}
{% for items in home %}
<h2>{{ items.title_en }}</h2>
<p>{{items.content_en}}</p>
{% endfor %}
{% endif %}
I hope it can be helpful
Related
I have two classes in my models, two defs in views and one template in one app. Just one of the functions doesn't work properly. Everything else works fine.
I double checked everything but didn't find the issue. Below the code:
Models
from django.db import models
class BildTextMarkt(models.Model):
fotomarkt = models.ImageField(upload_to='images/')
text = models.TextField(blank=True, max_length= 512)
views
def bildtextmarkt(request):
all_maerkte = BildTextMarkt.objects.all()
context = {'my_maerkte':all_maerkte}
return render(request, 'maerkte/maerkte.html', context)
templates
{% for maerkte2 in my_maerkte %}
<div class="bild">{{ maerkte2.fotomarkt }}</div>
<div>{{ maerkte2.text }} </div>
{% endfor %}
Thank you for any hints.
the imagefield item in the template should be
<img src="{{ maerkte2.fotomarkt.url }}">
I have a list of assets, created by different users. I'd like to show the assets for each user in a template.
Right now, I have this (there's more code, but not relevant for this issue):
models.py:
from django.db import models
from django.contrib.auth.models import User
from tinymce import models as tinymce_models
class Asset(models.Model):
title = models.CharField(max_length=200)
description = tinymce_models.HTMLField()
dateadded = models.DateField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
file = models.FileField(upload_to='images/', verbose_name='Image', null=True, blank=True)
url = models.URLField(max_length=500, blank=True, default='')
views.py
from .models import Asset
from django.contrib.auth.models import User
def assets(request):
assets = Asset.objects
users = User.objects
context = {'assets':assets, 'users':users}
return render(request, 'assets/assets.html', context)
But what should I put in my template? The following gives a list of all assets, but the second part should only show assets by 'bob' and eventually all assets listed by user (all assets by 'bob, all assets by 'pete', etc) regardless of the user being signed in.
{% for asset in assets.all %}
{% if asset.file %}
{{ asset.dateadded_pretty }} - {{ asset.title }} <span style="font-size:11px">
({{ asset.ext }} - {{ asset.size }})</span>
{% else %}
{{ asset.dateadded_pretty }} - {{ asset.title }} <span style="font-size:11px">
(external link)</span>
{% endif %}
<br>
{% endfor %}
<br><br><br>
Assets by Bob:
{% for asset in assets.all %}
{% if asset.user == "bob" %}
{{ user.title}}
{% endif %}
{% endfor %}
{% endblock %}
Thanks for any pointers!
First query all the users in view
def assets(request):
assets = Asset.objects.all()
users = User.objects.all()
context = {'assets':assets, 'users':users}
EDIT: you can filter the users who has assets like this.
users = User.objects.filter(id__in=assets)
Now in the template you can do like this to get the assets by individual user
{% for user in users %}
{{user.email}}
{% for asset in user.asset_set.all %}
{{ asset.title}}
{% endfor %}
{% endfor %}
I have the following models. I am trying to get the newlistitem model to inherit the same image from the above, if that makes sense. I see that I passed through user as a parameter when calling listitem.user and it works fine, but can't seem to grab the picture of the related object.
HTML Render
I am returning both objects to the form and call
{% for item in listitems %}
<div id = "indivlistitem">
<b>{{item.list_name|title}}</b>
<li><img src="/media/{{ item.list_picture }}"/></li>
<li>{{item|title}}</li>
</div>
{% endfor %}
#MODELS
from django.db import models
from django.contrib.auth.models import User
class newlist(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100)
picture = models.ImageField(upload_to='profiles/')
def __str__(self):
return self.list_name
class newlistitem(models.Model):
user = models.ForeignKey(User)
list_name = models.ForeignKey(newlist)
list_item = models.CharField(max_length = 200)
list_picture = models.ImageField(newlist.picture)
def __str__(self):
return self.list_item
First things first, list_picture = models.ImageField(newlist.picture)
is not going to work. However, it did provide some insight into what you're trying to do.
Since you already have a foreign key to a list in the newlistitem model (your list_name field), you can access the picture that it's linked to by traversing the foreign key, as such.
You'll note that I've also used the url property that all ImageFields contain, to automatically populate the URL of the picture:
{% for item in listitems %}
<div id = "indivlistitem">
<b>{{item.list_name|title}}</b>
<li><img src="{{ item.list_name.picture.url }}"/></li>
<li>{{item|title}}</li>
</div>
{% endfor %}
UPDATE
Some of the pictures that you are trying to access are blank, so you will need to validate that there is an image associated with each entry.
{% for item in listitems %}
<div id = "indivlistitem">
<b>{{item.list_name|title}}</b>
{% if item.list_name.picture %}
<li><img src="{{ item.list_name.picture.url }}"/></li>
{% endif %}
<li>{{item|title}}</li>
</div>
{% endfor %}
I'm using django-taggit on one of my projects and I'm able to save and tie the tags with specific records. Now the question is how do I display the tags related to each record?
For example on my page I want to display a record which contains a title and content and then under it I want to show the tags tied to that record.
What goes in the views.py, and mytemplate.html? Real examples would be truly appreciated.
models.py
from django.db import models
from taggit.managers import TaggableManager
class MyObject(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
tags = TaggableManager()
views.py
from django.views.generic import simple
def show_object(request):
""" View all objects """
return simple.direct_to_template(request,
template="folder/template.html",
extra_context={
'objects':MyObject.objects.all(),
})
template.html
{% for object in objects %}
<h2>{{ object.title }}</h2>
<p>{{ object.content }}</p>
<ul>
{% for tag in object.tags.all %}
<li> {{ tag.name }} </li>
{% endfor %}
</ul>
{% endfor %}
If you are in a hurry you can also try:
{{context_name.tags.all|join:", "}}
I want to use an app to create a menu that is easy to edit with the admin interface. Something like this:
class Menu_item
name = models.CharField()
item_url = models.URLField()
My template looks something like this:
{% extends base.html %}
div ID="nav"
{{ foo.navbar.? }}
/div
div ID="Content"
{% block content %}{% endblock %}
/div
I want div#nav to contain a ul based upon the above model but just can't figure out how to accomplish this. It seems like an object_list generic view would be great but, the URL accesses the view for the model that populates div#content. Does anyone have any suggestions? Is there a way to access a generic view without a URL?
Thank you.
I have discovered a solution. Inclusion Tags.
What I did was create an inclusion tag, which amounts to a simple custom template tag (django provides a shortcut for you!).
Here is what I did:
Ignore views.py - It will not be used in this case
Create a sub-directory in the app's dir called "templatetags" containing init.py and get_navbar.py (or whatever you want your tag to be):
mysite/
navbar/
templatetags/
__ init__.py (without the space befire init)
get_navbar.py
I changed my navbar.models to look like this:
from django.db import models
class Menu_choice(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Menu_item(models.Model):
name = models.CharField(max_length=20)
navbar = models.ForeignKey(Menu_choice)
item_url = models.CharField(max_length=200)
item_desc = models.CharField(max_length=30)
def __unicode__(self):
return self.name
This allows me to create a Menu_choice object in the admin interface for each layer of navigation (primary, secondary, etc)
get_navbar.py looks like this:
from navbar.models import Menu_choice, Menu_item
from django import template
register = template.Library()
#register.inclusion_tag('navbar/navbar.html')
def get_navbar(navBar):
navbar = Menu_item.objects.filter(navbar__name=navBar)
return { "navbar": navbar }
(Note navBar as opposed to navbar)
Create the navbar.html template:
<ul>
{% for menu_item in navbar %}
<li><a href="{{ menu_item.item_url }}">{{ menu_item.name }}</a></li>
{% endfor %}
</ul>
Finally, I inserted the following into my base.html:
{% load get_navbar %}
And where I want primary navigation:
{% get_navbar "primary" %}
Note: the quotes around the string you are sending to your inclusion tag are important. I spent a ridiculously lengthy bit of time trying to make it work before I figured that out.
Also a big thank you to dikamilo for the help.
First, in you view, get data from db:
def index(request):
navbar = Menu_item.objects.all()
return render_to_response( 'you_template.html',
{ 'navbar': navbar }, context_instance = RequestContext (request ) )
And in template:
<div id="nav">
<ul>
{% for i in navbar %}
<li>{{ i.name }}</li>
{% endfor %}
</ul>
</div>