A help in concept and a database query question (Django/Python) -


i trying build kind of news website learning purposes.

class newscategory(models.model):     category = models.charfield(max_length=50) 

note: category can soccer, tennis, business ... user can register different news category. choice saved in preferences.

class profile(models.model):     user = models.foreignkey(user, unique=true)     gender = models.charfield(max_length=1,blank=true)     preference = models.manytomanyfield(newscategory) 

i stuck on how update preference list of each user (the list specifies in categories interested in.)

view:

category = [(item.category) item in newscategory.objects.all()] 

and sending category template below

template:

<div id="c_b">     {% c in category %}         <input type="checkbox" name="category[]" value="{{c}}">         <label for="{{c}}">{{c}}</label>     {% endfor %} </div> 

questions:

  1. what best way add checked tag next checkboxes saved in user's preference when display template.

    i though of getting preferences users registered for: saved_preference = user.preference.all() , checking each item in category if in saved_preference

    i blanking out on way write code, , whether should done in view or template.

  2. what way update user preference list?

    i planning on running user.preference.clear() , going through every item in submitted form , running user.preference.add(the_new_preference)

you'll need pass complete list of categories , index of user-selected categories template. don't need convert newscategory queryset list in view, way:

view

categories = newscategory.objects.all() user_preferences = [item.id item in profile.preference.all()] 

the user_preferences variable act lookup index our template.

then loop through categories in template, , check see if exists in list of user preferences:

template

<div id="c_b"> {% c in categories %}     <input type="checkbox" name="category[]" id="id_{{ c.category }}" value="{{ c.id }}" {% if c.id in user_preferences %}checked="checked"{% endif %} />     <label for="id_{{ c.id }}">{{ c.category }}</label> {% endfor %} </div> 

update - saving user preferences

there no hard , fast rule here. main consideration, far concerned, minimising database hits. can clear user preferences, say, , add new ones - in fact, how django's admin handles it. make use of django's transaction management:

from django.db import transaction  @transaction.commit_manually def add_preferences(user, preferences):   user.preference.clear()   pref in preferences:     user.preference.add(pref)   transaction.commit() 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -