python - Retrieving and Displaying a ManyToMany field in Django from a OnetoOne Class -


i trying display list of trees user can 'heart' in django , having no luck.

models.py

from django.db import models django.contrib.auth.models import user   class tree(models.model):      treeid = models.integerfield(primary_key=true)     neighbourhood = models.charfield(max_length=128,blank=true)     commonname = models.charfield(max_length=128, blank=true)     diameter = models.floatfield(blank=true)     streetnumber = models.positivesmallintegerfield(blank=true)     street = models.charfield(max_length=128, blank=true)    class userprofile(models.model):     # line required. links userprofile user model instance.     user = models.onetoonefield(user)       # tree field used store user's favourite trees     tree = models.manytomanyfield(tree, blank=true) 

views.py

@login_required def favourites(request):      current_user = userprofile.objects.get(id=request.user.id)     tree_list = current_user.tree.all()     context_dict = {'trees' : tree_list}     return render(request, 'hug/favourites.html', context_dict) 

favourites.html

            {% tree in trees %}             <p>tree id   -   {{ tree.treeid }}</p>             <p> {{ tree.commonname|title }}</p>             {% endfor %} 

i have tried print statements , seems not line of code: tree_list = current_user.tree.all() (as not print anything) , when run code on server get:

userprofile matching query not exist. 

any advice appreciated.

thanks,

a

there few problems code.

firstly, tree model defines primary key integerfield, not autofield. means won't allocate ids automatically; integrityerror when try , add new trees. unless there reason this, should omit field , let django define own automatic id.

secondly, code userprofile wrong. trying userprofile id same current user's id. assumes ids in user , userprofile same; , there no reason assume that. why "does not exist" error: looking wrong id.

the correct way userprofile user doing:

user_profile = request.user.userprofile 

however, question why need userprofile model @ all. thing contains manytomanyfield; , since makes no difference side of relationship define on, why not put tree , make relationship directly user? avoids whole lookup , simplifies problem immensely. able do:

tree_list = request.user.tree.all() 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -