how to add property for ListField on mongoengine - django

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())

Related

django How get creator username instead id using two for

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 }}

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: defining a model to make a template

I am new to creating models in Django and I want to make a model, which allows you to fill in the title, some texts for on the template and the path to this template. I am trying to get the answer off of the Django Example Project, but I just don't understand the models, is there anybody who can help me on how to write such a model?
My code in the models.py
class Project(models.Model):
project_name = models.Charfield(max_length=20)
project_title = models.Charfield(max_length=100)
project_information = models.Charfield(max_length=400)
where project_name is the link to the template
I don't know if this is a correct begin or that it should be something completely different.
I'm assuming that you're asking ways to use the information in a model (object data) in a template.
If so, template isn't created in a model, you can send your object(s) to a template by rendering a template in the corresponding view of the model. You'll append the necessary information (queryset and other optional dict elements) in the view and send it to the template.
How you can use the information in the template depends on your view method. For function based views like this:
def home_view(request):
contests = Contests.objects.filter(id<5)
context={'contests':contests}
return render(request, 'home/home.html', context)
You can access the data in a queryset in the template, like this:
{% for contest in contests %}
//do something with the single contest data
{% endfor %}
You can directly access the non-plural values like this:
{% if not random_contest == None %}
//do something with the random contest data
{% endif %}
Additionally, there are class based views but it looks like you are at a very early stage of learning Django, so you won't need it for now.
See the docs about views.
See the docs about shortcut functions.

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

Django template can't access a form field if it is inside an array

Fairly new to Django here, so I don't know if I'm just not getting it or this is a bug. Let's say I have a form class:
class SurveyTwo(forms.Form):
food = [forms.BooleanField(required=False, initial=False, label="Seafood")]
Then, in the corresponding template, I am trying to access this by typing
{{ form.food.0 }}
When I do this, I get on my page:
<django.forms.fields.BooleanField object at 0x1c5b990>
Not the "Seafood" checkbox I was looking for. I can access the label just fine by doing {{ form.food.0.label }} but the checkbox just appears as that string. Should I be able to do this or not?
Essentially what I am trying to do is to pass an array of checkboxes to my form template, rather than having to define each form variable/field. I want to do this because I'm going to have a large number of checkboxes and want to be able to lay them out in a certain order (with a 2D array), rather than define them and lay them all out manually. If I can't do the above, does anyone know of a simpler solution? Thanks.
Mark
You can register simple template tag:
from django import template
register = template.Library()
#register.simple_tag
def bound_field(form, name):
""" returns bound field """
return form.__getitem__(name)
Then in template you just use:
{% bound_field form <field_name> %}
where is name of field.
If you have dynamicly generated fields that names you don't know you can access to them via fields.keys in this case generating all fields will look like
{% for name in form.fields.keys %}
{% bound_field form name %}
{% endfor %}