一个用户在Django中查看另一个用户配置文件

2024-05-13 21:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想实现另一个用户a单击另一个用户B的图片并自动重定向到用户B的配置文件的功能。我如何做到这一点?请看我的HTML,我在那里说了一些关于链接的东西

view.py

class profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
bio = models.TextField(blank=True)


def __str__(self):
    return f'{self.user.username} profile'

html:

{% for post in posts %}
  <div class="icl-NavigationList-item">
   <div class="icl-NavigationList-link icl-NavigationList--primary">
   <div class="icl-NavigationList-text">
   <h2 class="icl-NavigationList-title">
     <div class="upperText">
      <h2 class="card-title"style="background-color:{{post.post_colours}};">{{post.job_title}}</h2>
    <a class="a-tags" href="*{{ i need to link the post author's profile  here}}*" data-tippy-content="@dribble_handle">
  <img  src="{{post.author.profile.profile_pic.url}}" style="border-radius: 100%;float:right;" 
  alt="author"width="30" height="30"></a></div>
  <div class="lowerText"> <p class="card-text">{{post.currency}} {{post.salary}}</p>
   <p class="card-text"> Posted on {{post.date_posted}} by {{post.author}} </p>
  <br>
   {% if user.is_authenticated %}

我的模型

class profile(models.Model):
   user = models.OneToOneField(User, on_delete = models.CASCADE)
   bio = models.TextField(blank=True)
  category = models.CharField(max_length= 1000, choices = 
  Select_category,default='other')



def get(self, request, *args, **kwargs):
    username = self.kwargs['username']
    user_profile = profile.objects.get(user__username=username)
    gigs = Gig.objects.filter(user__username=username, status=True)
    print(user_profile.values())
    return render(request, 'blog/profile.html', {'user_profile': user_profile, 'gigs': gigs,'name': username})

Tags: text用户selfdivtrueonmodelsusername
1条回答
网友
1楼 · 发布于 2024-05-13 21:30:13

好的,这里有一个经过编辑的答案。我看了一下你的代码,这里没有post模型,所以我只是想把一些片段放在一起试试。最终,我们的目标应该是让href如下所示:

href=“{post.author.get_absolute_url}”

这里请注意,它不是{{post.author.profile.get_absolute_url}。在url中省略概要文件似乎有违直觉,但请记住,传递的用户名参数是用户模型的一部分,而不是概要文件模型

(注意:url肯定取决于您文章的模型。如果作者是用户模型的外键,请使用我在此处键入的内容。如果是与配置文件模型相关的外键,您将用author.user替换作者)

如果这不起作用,请确保URL.py设置正确

url.py

...
path(‘URL_YOU_WANT/<username>/, views.VIEW_NAME, name=“NAME”),
...

(注意:保持“<;username>;”与此完全相同。这是Django知道如何期望您的href传递username参数的方式。)

如果事情仍然不起作用,我会重写你的views.py视图以使其更清晰。您的views.py和models.py存在一些冗余和混乱。下面是我将如何着手的:

型号.py

class profile(models.Model):
     user = models.OneToOneField(User, on_delete = models.CASCADE)
     bio = models.TextField(blank = True)

     def __str__(self):
           return f’{self.user.username} profile’

视图.py

def user_profile(request, username):
     user = User.objects.get(username = username)
     user_profile = profile.objects.get(user = user)
     gigs = Gig.objects.filter(user = user, status = True)
     return render(request, ‘blog/profile.html’, {‘user_profile’: user_profile, ‘gigs’: gigs, ‘name’: username})

让我知道这是否有帮助

相关问题 更多 >