如何在Django中保存用户最喜欢的帖子

时间:2018-03-04 18:06:27

标签: python django

所以,我试图让用户喜欢一个帖子(在我的案例中为特价),稍后会在他们的个人资料页面上显示。

**更新 - 我遇到的问题 - 当提交保存收藏夹的表单时,收藏夹不会保存在数据库中。

我从这篇文章获得了我最初的灵感here

所以我在我的用户模型中添加了一个“收藏夹”字段,在我的交易模型中有多对多关系......就像这样:

favorites = models.ManyToManyField(Deal, related_name='favorited_by')

我的html模板,用户可以在此处收藏'Deal',如下所示:

<form id="favorite{{deal_detail.id}}" method="POST" action="{% url 'deals:favorite' deal_detail.id %}">
                            {% csrf_token %}
                            <input type="hidden" name="supporttype" />
                            <input type="submit" value="Add Deal to Favorites" />

我最喜欢的网址是:

url(r'^(?P<pk>[0-9]+)/favorite', favorite, name='favorite')

这是'deal_detail'和'favorite'

的视图
def deal_by_detail(request, slug):
    deal_detail = Deal.objects.get(slug=slug)
    return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail})


def favorite(request, pk):
    if request.method == 'POST':
        deal = Deal.objects.get(pk=pk)
        deal.save()
        messages.add_message(request, messages.INFO, 'Deal Favorited.')
        return redirect('home')

以下是我的完整用户和优惠模式:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})
    username = models.CharField(max_length=40, default='')
    first_name = models.CharField(max_length=40, default='', blank=True)
    last_name = models.CharField(max_length=40, default='', blank=True)
    date_joined = models.DateTimeField(default=timezone.now)
    favorites = models.ManyToManyField(Deal, related_name='favorited_by', null=True, blank=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

class Deal(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=140, unique=True)
    description = models.TextField(default='')
    retailer = models.ForeignKey(Retailer)
    image = VersatileImageField('deal image',
                               upload_to=deal_upload_path,
                               null=True,
                               blank=True)
    link = models.URLField(default='')
    category = models.ForeignKey(Category)
    date_added = models.DateField(default=timezone.now)
    date_expires = models.DateField(default=timezone.now)
    price = models.CharField(max_length=140)
    secondary_price = models.CharField(max_length=140, default='')
    likes_total = models.IntegerField(default=1)

1 个答案:

答案 0 :(得分:0)

好的,所以我不确定这是否是完美的方法,但它似乎有效。我创建了一个变量'favorite'来抓取所选项目,然后保存在用户对象中。

def favorite(request, pk):
    if request.method == 'POST':
        favorite = Deal.objects.get(pk=pk)
        user = request.user
        user.favorites.add(favorite)
        messages.add_message(request, messages.INFO, 'Deal Favorited.')
        return redirect('home')