我想在相关用户的个人资料中使用Django中的模板标签显示用户的产品

时间:2019-03-09 19:56:07

标签: python django templatetags

我用view.py(出生日期等)呈现用户的个人资料页面。 但是我应该显示有关个人资料页面所有者的产品(个人资料所有者的产品)。我建立了自定义用户模型,但无法在此模型中添加相关产品。

models.py

class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        slug = models.SlugField(max_length=55, blank=True, null=True)
        bio = models.TextField(max_length=500, blank=True)
        location = models.CharField(max_length=30, blank=True)
        birth_date = models.DateField(null=True, blank=True)
        avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
        products = models.ManyToManyField(Product, blank=True, related_name="Products")
        followers = models.ManyToManyField(User, null=True, blank=True, verbose_name="Followers", related_name="Followers")
        country = models.CharField(max_length=30, blank=True)
        job = models.CharField(max_length=30, blank=True)

        def save(self, *args, **kwargs):
            print(self.user.username)

            if not self.slug:
                self.slug = self.get_slug()
                print(self.slug)
            print(self.user.username)
            super(Profile, self).save(*args, **kwargs)

        def __str__(self):
            return "{username}".format(username=self.user.username)

        def get_slug(self):
            slug = self.user.username.replace("ı", "i")
            return slugify(slug)


    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)


    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()

views.py

@login_required
    def profile(request, slug):
        #  detail = Profile.objects.filter(id=id)
        #  profile_detail = Profile.objects.filter(slug=slug)
        profile_detail = get_object_or_404(Profile, slug=slug)
        context = {
            "profile_detail": profile_detail
        }
        return render(request, "profile_pages/profile.html", context)

user_template_tags.py

@register.simple_tag
def user_products(request):
    user = #  Profile page owner's username (HOW?)
    products = Product.objects.filter(seller=user)

    return products

urls.py

urlpatterns = [
    path('sign_up/', views.sign_up, name="sign_up"),
    path('login/', views.login_user, name="login"),
    path('logout/', views.logout_user, name="logout"),
    path('reset_password/', views.send_reset_link, name="reset_password"),
    path('create_new_password/', views.create_new_password, name="create_new_password"),
    path('profile/<slug:slug>/', views.profile, name="profile"),

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,您的过滤器毫无意义;您不需要它。

您正在将配置文件作为profile_detail发送到模板。因此,您可以使用它:

{% for product in profile_detail.products.all %}
    {{ product.name }} # or whatever
{% endfor %}