django How get creator username instead id using two for - django

I want get creator username instead id.
The item.r.username dont work.
item.r.bornplace work correctly.
Where i do mistake?
My model.py:
class Rec(models.Model):
creator = models.ForeignKey(auth.get_user_model(), on_delete=models.CASCADE)
bornplace = models.CharField(default='default')
My views.py
def lists(request):
list = Rec.objects.all()
lists = []
for r in list:
lists.append({'r':r})
context = {'lists': lists}
return render(request, 'lists.html', context)
My lists.html
{% for item in lists %}
{{ item.r.username }}
{{ item.r.author_id }}
{{ item.r.bornplace }}
{% endfor %}

For your issue you should use the Foreign Key mapping in the model fields you have defined from creator as defined below:
class Rec(models.Model):
...
creator = models.ForeignKey(auth.get_user_model(), on_delete=models.CASCADE)
In this instance I can see you are using Django's auth, and without going into too much detail their default model stores username, so from that your username attr can be accessed from your creator instance. With that, overall your template call should have been:
{{ item.r.creator.username }}
But this idea is not specific to Django's auth system, for all FK relationships defined in your models you can use the standard syntax to access fields as needed, both in templates and in views.
Models have attributes so use nested access to gather the values you need. For example:
model.FKField.field or model.FKField.method()
Naturally in templates there are no parentheses, so for using a method in a template the syntax is:
{{ model.FKField.method }}

you should do it in this way:
{{ item.r.creator.username }}

Related

Django filter related_name subset in templates

I have a foreign key and I'm using the related_name field like so:
class Pizza(models.Model):
...
restaurant = models.ForeignKey('Restaurant', related_name='pizzas_offered')
active = models.BooleanField(...)
...
Example from the view:
my_restaurant = get_object_or_404(Restaurant, pk=id)
In any template I can run something like my_restaurant.pizzas_offered.all to get all the pizzas belonging to a particular restaurant. However, I only want the pizzas that are active (active=True). Is there a way to retrieve this subset in the template, without having to pass a separate variable in the view? Please note that I always want to only show the active pizzas only so if I have to make a change in the model to make this happen, that is fine too.
NOTE: in the view I can simply pass my_restaurant.pizzas_offered.filter(active=True) but it returns an error when I use it in the template:
{% for details in my_restaurant.pizzas_offered.filter(active=True) %}
{{ details.name }}
{% endfor %}
It returns this error:
Could not parse the remainder: '(active=True)'
There are some reasons why I want to do this on template level and not in the view (main reason: I often loop through all the records in the database and not just one restaurant, so I can't just query for the one record). So my question is how to do this on template-level.
You need to create a Manager for your Pizza model and set the Meta.base_manager_name:
class PizzaManager(models.Manager):
def active(self):
return self.filter(status=True)
class Pizza(models.Model):
...
objects = PizzaManager()
class meta:
base_manager_name = 'objects'
Now you can use the method active in your template:
{% for details in my_restaurant.pizzas_offered.active %}
...
{% endfor %}
For more information you can read the documentation about Default and Base managers.

Django UpdatView - custom form fields

I have my UpdateView for updating some of my data.
class WpisUpdate(UpdateView):
model=ProdukcjaStanTb
fields=[
'temat',
'podtemat',
'proc_wym',
'proc_auto',
'proc_palnik',
'proc_uruch',
'proc_pakowanie',
]
Now, in my template I'd like to have only :
'proc_wym',
'proc_auto
'proc_palnik',
'proc_uruch',
'proc_pakowanie',
Fields, but also have access to fields "temat" and "podtemat" (to make big titles or web page title for example). In template i'm using {{form.temat.value}} tags, which are ok, but requires those fields in field list in UpdateView. I don't want user to change that. Is there any quick way to have those fields hidden in form but accessible while using easy:
{{ form.as_p }}
in template ? Or do i have to manually edit my form and add some html attributes, like read-only or input type="hidden" ?
Since this view only updates object you can always exclude unnecessary fields from autogenerated modelform - simply del them from your fields declaration then access 'temat', 'podtemat' in your template using object
template
{{ object.temat }} {{ object.podtemat }} {{ form.as_p }}
view
class WpisUpdate(UpdateView):
model = ProdukcjaStanTb
fields=[
'proc_wym',
'proc_auto',
'proc_palnik',
'proc_uruch',
'proc_pakowanie',
]

Django Foreign Key to Permission

class Application(models.Model):
name = models.CharField(max_length=100)
icon_url = models.CharField(max_length=100)
app_url = models.CharField(max_length=200)
I would like to add another field for required_permission which should be a foreign key to a permission. What should that field definition look like?
The reasoning behind this is that in a template, I can use something like this (psuedo code)
{% for app in application_list %}
{% if user_has_permission(app.required_permission) %}
Show App
{% endif %}
{% endfor %}
Your required_permission can be a CharField. As long as you can create a list of permissions to use with this function.
has_perms(perm_list, obj=None)
Returns True if the user has each of the specified permissions, where
each perm is in the format "<app label>.<permission codename>". If the
user is inactive, this method will always return False.
If obj is passed in, this method won’t check for permissions for the
model, but for the specific object.
Note that you can't call function that takes parameter in Django templates, You should write a template tag.

how to add property for ListField on mongoengine

I use mongoengine, and love it very.
now I work it with django, and I get a problem with it
how to set property for ListField
e.g.
this was my model
class Bussiness(Document):
tags = ListField(StringField())
and I want to use it on template like this:
{% for tag on bussiness.tags %}
{{ tag.url }}
{% endfor %}
but the tag.url I don't want to save it to database, just hope to produce it on model level, and make tags only some string on database.
And if I hard code it on template, I have to write it everywhere, that was I disgust.
This wont work as tag is just a string (you have it defined as a StringField).
You could have tag as an embedded document with url being a property eg:
class Tag(EmbeddedDocument):
name = StringField()
#property
def url(self):
return "http://my-ace-site.come/businesses/%s/"
class Business(Document):
tags = ListField(StringField())

Overiding placholders in django cms?

Hey im using the placeholder fields from django cms in some of my custom cms apps. Basically what im trying to achieve is specific styles and filters for the same placeholder fields being used in different templates.
for example if i have a model for vacancies that looks something like this:
from django.db import models
from cms.models.fields import PlaceholderField
# Create your models here.
class Vaccancy(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique = True)
ref_number = models.CharField(max_length=255)
info = PlaceholderField('info')
active = models.BooleanField(default=True, verbose_name="posistion active?")
and another model that also utilizes the placeholder field in a similar way. What i hoped i could do is overide the tex.html template then have some conditional logic to detect the name of the placeholder like so
{% ifequal placeholder "info" %}
{{ body|truncatewords:200|safe }}
{% endifequal %} the aim of this is so i can specify different filters like truncatewords etc as i dont want to apply this to every placeholder that uses a text plugin!
hope that was clear enough! cheers for any help!
If you use placeholder fields, you have to check for placeholder.slot, also note that {% if placeholder.slot == "info" %} seems a bit nicer than ifequal :D