List objects from a dictionary in Django - Creating Templates

Asked

Viewed 1,060 times

1

I’m trying to learn something about Django, and a doubt has arisen.

I have a dictionary with several keys and valuables. The idea is, for each key, to display a list of values with checkboxes that can be selected to perform other tasks below.

But I don’t understand how I can create models and then correlate keys with values using checkboxes in Django, someone could give me a light?

1 answer

1


wouldn’t be the idea?

model py.

class BookModel(models.Model):
  title=models.CharField()

class User(models.Model):
  username=models.CharField()

class Recommend(models.Model):
  user=models.ForeignKey(User)
  book=models.ForeignKey(BookModel)
  friends=models.ManyToManyField(User, related_name="recommended")

html template.

{% for friend in friends %}

<input type="checkbox" name="recommendations" id="option{{friend.id}}" value={{friend.username}} />
<label for="option{{friend.id}}"><b>{{friend.username}}</b></label><br />

{% endfor %}
  • That, that’s the idea, thank you! A question, how could I pass the dictionary so that these templates were filled in? I’m still a little lost in Django and the tutorials are very specific!

  • Hummm, dude, you need to enter the dictionary data using Django’s Orm, using the example q postei would look more or less like user = User(username="name"). save() book = Bookmodel(title="title"). save() Recommend(user=user,book=book). save() #after entering the records, make the query in Recommend.Friends(). values() #Django is complicated to explain, but it becomes simple and quick to create things with it when we get the game

  • Beauty man, thanks for the tips! I’ll try here!

  • let’s say I have the following dictionary of users = {"user1":"user_name1","user2":"user_name2"} dai vc creates a for nesse usuarios like: for key,value in usuarios.items(): and for each input of for vc add in User like this: user = User(username=value) user.save() ...and so on, vc inserts the user into Recommend and ready, then creates a new function in your view to fetch this data with Recommend.Friends(). values()

  • Oh yes, I understood how it works after digging a little! But I was left with another question! If the dictionary is of the type {a:[F1,F2,F3], a2:[F3,F4,F5]...}, how could I save it? I tried using this template but on the admin page I get a column to select a, f, and a relation Many to Many. I wish there was only the attribute and I could relate it to Fs (they are more than one for each attribute!). Actually the doubt is how to relate the "a" with its "Fs" in such a way that in the administration page appear only one column of attributes and another with the relation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.