【发布时间】:2020-08-02 08:43:36
【问题描述】:
我正在开发一个涉及各种人员、公司和产品的 Django 应用程序。我想包括让登录用户“收藏”任意数量的人、公司和产品的能力。我是一个非常新的 Django 开发人员,我对 Javascript 的了解很少,所以我很难将现有的 Django/Ajax 教程应用于我的情况。这是我到目前为止所拥有的。我将仅包括有关偏爱某人的部分内容,因为我认为偏爱公司和产品的解决方案几乎相同。
# models.py (relevant tables only)
class Person(models.Model):
first_name = models.CharField(max_length=50)
middle_name = models.CharField(max_length=50, blank=True)
# many other irrelevant fields omitted
class CustomUser(AbstractUser):
fav_people = models.ManyToManyField(Person,
through='FavoritePerson',
through_fields=('user', 'person'),
related_name='users',
)
fav_companies = models.ManyToManyField(Company,
through='FavoriteCompany',
through_fields=('user', 'company'),
related_name='users',
)
fav_products = models.ManyToManyField(Product,
through='FavoriteProduct',
through_fields=('user', 'product'),
related_name='users',
)
class Meta:
verbose_name_plural = 'Custom Users'
def __str__(self):
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
else:
return f"{self.username}"
class FavoritePerson(models.Model):
user = models.ForeignKey(CustomUser,
on_delete=models.CASCADE,
related_name='favorite_people'
)
person = models.ForeignKey(Person,
on_delete=models.CASCADE,
null=True,
blank=True,
related_name='favorite_people', )
created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Favorited People'
def __str__(self):
return f"{self.user} - {self.person}"
这是我的模板的相关部分,如果此人不是收藏夹,它会显示一个星形轮廓,如果此人是登录用户的收藏夹,它会显示一个填充的星形。我正在为图标使用django-fontawesome-5 包。
<!-- person_detail.html -->
<section id="entity-details">
<div class="container">
<div id="entity-bio-col">
{% if person in user.fav_people.all %}
{% fa5_icon 'star' 'fas' color='white' size='fa-xs' title='One of your favorite pros' %}
{% else %}
{% fa5_icon 'star' 'far' color='white' size='fa-xs' title='Favorite this pro' %}
{% endif %}
</div>
</div>
</section>
我需要做的就是在我单击星形轮廓时在 FavoritePerson 表中插入一行,并在我单击填充星形时删除表中的该行。我希望它在没有页面刷新的情况下工作,因此使用 Ajax 方法。
有人愿意提供解决方案吗?我可以拿着它从那里跑。
【问题讨论】:
标签: jquery django ajax django-forms django-views