On Sunday, 12 February 2012 11:06:32 UTC, richard wrote:
>
> Hi im having difficulty looping over my mantomany in my template. A 
> user has a 1to1 with UserProfile and the UserProfile has a manytomany 
> with interests. But displaying the form field without looping over it 
> displays a model multiple select with just a list of object result 
> sets. displaying interests object in the list. 
>
> code 
> models.py 
>
> class Interests(models.Model): 
>     # eg hockey, gaming, etc 
>     interest = models.CharField(max_length=100) 
>     class Meta: 
>         db_table = u'interests' 
>
> class UserProfile(models.Model): 
>     user = models.OneToOneField(User) 
>     interests = models.ManyToManyField(Interests) 
>
> forms.py 
> class ProfileEditForm(ModelForm): 
>     class Meta: 
>         model = UserProfile 
>
> views.py 
> def edit(request): 
>     c = {} 
>     c.update(csrf(request)) 
>     profile_edit_form = 
> ProfileEditForm(instance=request.user.get_profile()) 
>     if request.method == "POST": 
>         pass 
>
>     c['profile_edit_form'] = profile_edit_form 
>     return render_to_response('profile.html', c, 
>            context_instance=RequestContext(request)) 
>
> template 
> {{ profile_edit_form.interests}} # which displays multipleselect with 
> values as 'interests object' becuase i cant loop over it to get 
> interest 
>
> heres my attempts to loop over it 
> attempt 1 
> {% for interest in profile_edit_form.interests.all %} # seems to be no 
> results in all 
>     {{ interest.interest }} 
> { % endfor %} 
>
> attempt2 
> {% for interest in profile_edit_form.interests_set.all %} # seems to 
> be no results in all 
>     {{ interest.interest }} 
> { % endfor %} 
>
> attempt3 
> {% for interest in profile_edit_form.userprofile_interests.all %} # 
> seems to be no results in all 
>     {{ interest.interest }} 
> { % endfor %} 
>
> Am i going wrong somehow.? 
>
> thanks. 
>
>
>
You're trying to iterate over a form field as if it's a model field or a 
queryset, which it isn't. `user_profile.interests` has an `.all()` manager, 
but `profile_form.interests` doesn't. 

As pw points out, if you define a `unicode` on the interests class, its 
value will be used when rendering the field. Otherwise, as the 
documentation[1] states, you can subclass ModelChoiceField to override 
`label_from_instance` to return a custom value.

 [1]: https://docs.djangoproject.com/en/1.3/ref/forms/fields/#modelchoicefield
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/ghs43wOja1kJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to