Django ManyToManyField在行动

时间:2014-07-16 19:30:20

标签: python django django-templates manytomanyfield

我有这样的models.py:

 class Entry(models.Model):
        user = models.ForeignKey(User, null=True, blank=True)
        baslik = models.ForeignKey(Baslik, null=True, blank=True)
        icerik = models.TextField(max_length=50000)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
        updated = models.DateTimeField(auto_now_add=False, auto_now=True)

        def __unicode__(self):
            return str(self.icerik)

    class Favorite(object):
        user = models.ForeignKey(User, null=True, blank=True)
        favs = models.ManyToManyField(Entry)

我想在模板中为用户的收藏夹列表添加一个条目,其中包含一个链接:

<div>
            <p>{{ entry}}</p><a href="link">Add to favs</a>
</div>

我该怎么办?我是新来的,所以请解释一下。 感谢。

1 个答案:

答案 0 :(得分:0)

我将在你的案件中做些什么:

创建一个向用户添加条目的视图:

def add_fav(request, entry_pk):
    entry = get_object_or_404(Entry, pk=entry_pk) #Will return you the entry with pk= entry_pk or 404 if does not exist
    #Now we try to check if user already have fav or not
    try:
        favorite = Favorite.objects.get(user=request.user)
    except Favorite.DoesNotExist:
        #If not we create a new favorite object
        favorite = Favorite.objects.create(user=request.user)
    #Then we add the entry to favs
    favorite.favs.add(entry)
    #And we save
    favorite.save()

然后您只需调用视图即可将该条目添加为用户收藏,因此在 urls.py

url(r'^addfav/(?P<entry_pk>\d+)$', 'myapp.views.add_fav', name='myapp_add_fav')

然后在您的模板中,您可以执行类似

的操作
<a href="{% url 'myapp_add_fav' entry_pk=entry.pk %}">Add to favs</a>

希望很清楚