我有一个叫做Product
的模型,它有一个user
字段,还有一个Profile
模型,它也有一个user
字段。我想要的是:当user
A
从Product
模型发布一些东西时,user
B
也从Product
模型发布一些东西,我想将访问者或其他用户重定向到创建该Product
模型对象的用户的public_profile
页面。
例如:在Stack Overflow中,当用户问一个问题时,你可以在这个问题上看到他们的用户名,并且世界上任何人都可以访问创建这个问题的用户的个人资料页面。
网址:
path('/<slug:slug>/', views.public_profile, name='Public-Profile'),
视图:
def public_profile(request, slug):
return render(request, 'public_profile.html')
我的模板:{% for product in products %}
<div class="col-md-3">
<div class="card my-2 shadow-sm bg-body">
<div class="card-head">
I want add the url to this `a` tag
<a href="{% url 'Public-Profile' %}">
<span class="material-symbols-outlined">
account_circle
</span>
{{ user.username }}
</a>
</div>
{% endfor %}
我的模型:
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
description = models.TextField(max_length=1000)
image = models.ImageField(upload_to='product-image')
price = models.FloatField(max_length=11)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
phone_number = PhoneNumberField()
created_at = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def __str__(self):
return str(self.name)
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile_photo = models.ImageField(upload_to='profile-image', default='static/dafault.jpg')
twitter = models.URLField(blank=True, null=True, unique=True)
website = models.URLField(blank=True, null=True, unique=True)
linkedln = models.URLField(blank=True, null=True, unique=True)
country = models.CharField(max_length=70, blank=True, null=True,)
about = models.TextField(max_length=700, blank=True, null=True)
slug = models.SlugField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.user)
super().save(*args, **kwargs)
def __str__(self):
return str(self.user)
尝试在url中添加slug
参数,这将导致产品相关的用户配置文件段符product.user.profile.slug
{% for product in products %}
<div class="col-md-3">
<div class="card my-2 shadow-sm bg-body">
<div class="card-head">
<a href="{% url 'Public-Profile' slug=product.user.profile.slug %}">
<span class="material-symbols-outlined">
account_circle
</span>
{{ product.user.username }}
</a>
</div>
</div>
</div>
{% endfor %}
您可以在您的Product模型中添加一个方法get_user_public_profile_url
,它返回Product .user的概要URL
from django.urls import reverse
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
...
def get_user_public_profile_url(self):
return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug})
,在你的模板中,修改这一行
<a href="{% url 'Public-Profile' %}">
<a href="{{ product.get_user_public_profile_url }}">