Reverse query on django extended user profile - django-models

I have extended User via AUTH_PROFILE_MODULE to include a ManyToMany field to Projects the user is involved in.
I want to reverse the relationship, and get the Users associated with a given Project.
My users have profiles (I've successfully returned them with related_projects = u.profile.projects).
related_users = project.userprofile_set.all() is giving me something - {% for user in related_users %} {{ user }} {% endfor %} yields User Profile for: richlyon. But I can't get {{ user }} to yield any fields. I've tried {{ user.username }}.
Question: am I going about this the wrong way? And if I'm not, how do I get field information out of a reverse relationship on an extended User profile?
Thanks as always for your time.

Your 'profile' object is not a User, nor is it extending User (in an object-oriented sense). Rather, it's a separate model that has a ForeignKey to a User.
User > Profile > Projects
In the code you posted, it looks like you're expecting a User object to be returned from the project.userprofile_set.all() query set. However, these are going to be your intermediate profile objects from which you can then access the user.
Something like this:
related_profiles = project.userprofile_set.all()
{% for profile in related_profiles %}
{{ profile.user.username }}
{% endfor %}

Related

Symfony2 - Generate input fields based on entity

I'm having a trouble with creating a dynamic form in Symfony2.
What i wanna do is to register a collection of text field which are generated from an entity.
I dont know where to start exactly but here's a kinda of pseudo-code of what im trying to do :
in my view :
{# list_type_url are retrieved from DB #}
{% for url in list_type_url %}
<input type="text" name="link[{{ url.name }}]">
{% endfor %}
I started in my form builder with this :
$builder->add('link', CollectionType::class)
but I dont know how to link the array in the view with the form.
Maybe Im thinking it wrong ?
EDIT:
I edit the post to make things clearer :
the list_type_url variable is coming from an another entity. Let's says it is named UrlType, in which I can create a type of url.
Then in an another entity, imagine "Contact", i want to be able to add all the type of existing url.
so concretely, I could create 3 types of url or more (lets say top, middle, bottom) and in my contact form, i have to display those 3 types and fill them with different urls and i should be able to retrieve each of the types for a particular contact.
I've also readed how to dynamically modify forms but I really don't see how to use it with my problem
I hope i get more clearier

GAE: Efficiently querying entities and their referenced entities

I am trying to efficiently return a list of entities, and their respective referenced entities in a template view. For example
We are working with two Kinds:
class Event(ndb.Model):
"""An fun activity or event"""
name = ndb.StringProperty()
venue = ndb.KeyProperty()
class Venue(ndb.Model):
"""The venue of an event"""
name = ndb.StringProperty()
address = StringProperty()
The Event kind references Venue via an ndb.KeyProperty(). To display a list of events and their respective venues into a template, I can first do this query:
# we can fetch this from memcache
events = Event.query().fetch()
Then, in my view:
{% for event in events %}
Event Name: {{event.name}}
Event Venue: {{event.venue.get().name}} # is this line costly?
{% endfor %}
With this method, I think that for each event, there will be get() call for its respective venue. If this is true, it sounds expensive. Assuming that there are 100 events. Each page load would incur 100 event.venue.get().name requests. This means that a modest 10000 page views per day would incur 10000 * 100 .get() requests. Does that sound correct?
Is this the best approach to this problem? If not, what options can I consider?
First, depending on the total number of venues in your dataset, they may all easily fit into Memcache. So unless a venue is modified, you can go for days without touching the datastore - regardless of the number of page views. Make sure you use Memcache for your venues too.
Second, a more efficient way to retrieve entities is in a batch request. Loop through your events, create a list of all venues that you need (by the way, which may be smaller than the number of events if several events happen in the same venue - I don't see that check in your code), then issue a batch request for all venues.
Here is the Python code to fetch all of the venue names:
venue_keys = set(event.venue for event in events)
venues = ndb.get_multi(venue_keys)
venue_name = {venue.key, venue.name for venue in venues}
Then, in your template, you can use:
Event Venue: {{ venue_name.get(event.venue, 'No venue') }}

Twig create array and place them in specific places

I'm pretty new to Twig and can't figure one thing out!
I'm trying to create a homepage where in different spots images need to be placed. I know this can be done by executing a function where an image need to be placed. Problem is that I have to do that 7 times on one page.
So my question is if you can create some sort of array and then get the results from the array in the appropiate spots.
See below
Let's say I want to place an image in A,D,E,G. What would be the quickest way to accomplish that? What I already can do is
{% for product in products %}
{% endfor %}

Django reading model data in a template

I'm new to django and am having trouble reading data from a model in a template.
Here's the model.
class Team(models.Model):
team_name = models.CharField(max_length=30, default="Team")
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.team_name
The view.
def create_team(request):
team = Team.objects.all()
return render_to_response("ideas/profile.html", {'team':team})
And the template.
<h2>Available groups: {{team.team_name}} </h2>
Likelihood this is an obvious fix: 99%. Thanks anyway guys!
team is not an object, it's a queryset -- simplistically, a list of objects. Even if there's only one object in the table, it's simply a list of one. As a result, you can't just reference model attributes on it as if it were an instance of the model -- you have to pull the instance out first:
{% for t in team %}
{{ t.team_name }}
{% endfor %}
A couple of notes. As the loop shows, naming it team doesn't make sense. That implies one thing, and now we're going to loop through a single entity? Best practice here is to name single items singular and querysets, lists, etc. plural. Then we would do for team in teams which makes a lot more sense.
Secondly, don't use the model name in the attribute name. team.team_name is redundant, when team.name would work just as well. If there's another "name" attribute, then prefix that one, but the model itself should have priority on top-level attribute names.

String conversion within GAE webapp template

I am trying to create a string of the key of a ReferenceProperty within a webapp template:
Assume the following simple datastore model:
def User(db.Model):
first_name = StringProperty()
last_name = StringProperty()
def Email(db.Model):
user = ReferenceProperty(User)
email = EmailProperty()
I then pass a list of Email entities to a webapp template in list named member_list. Within the template, I want to create a string of the key of each Email entity's 'user' property for use in a URL, such as:
{% for member in member_list %}
<a href="/member_handler/{{INSERT_STRING_OF_MEMBER.USER_KEY_HERE"}}>blah</a>
I realize I could pass a string of the key to the template, but I would prefer to do the string conversion in template if possible; I have tried various permutations of str() and _ str_ to no avail.
Since you know the entity in question will be a Member instance, and presumably won't have a parent entity, it's much simpler (and produces nicer URLs) to use the key name or ID of the member, rather than the full string key. You can get this with user.key().name() (user.key.name in a Django template) or user.key().id(). Which one you need depends on whether you created the entity with a key name or not.
If you have an email object, there's no need to fetch the User from it just to get its key. Instead, call Email.user.get_value_for_datastore(member), which will return the Key object of the User it references. You can then extract the relevant field as you wish. There's no way to do this in Django, though, so you'll either need to do it outside Django and pass it in, or add a method to the Email class that returns the key.
Once you have an ID or Name and want to fetch the User object it references, call User.get_by_id(id) or User.get_by_key_name(name) as appropriate.
member.user.key should do the trick:
{% for member in member_list %}
<a href="/member_handler/{{member.user.key"}}>blah</a>
blah

Resources