简体   繁体   中英

Django 2 implement Other user's Profile View

I'm working on a project using Python(3.7) and Django(2.1) in which I need to implement a view for users to view other user's profile, I have implemented the view, it shows the profile but displaying the profile information.

Here what I have tried:

From models.py :

class ProfileModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profile')
    avatar = models.CharField(max_length=500, null=True, blank=True)
    about = models.CharField(max_length=1000, null=True)
    slogan = models.CharField(max_length=500, null=True)
    profile_pic = models.ImageField(default='/assets/images/avatar.png', upload_to='profile_pics', null=True)

    def __str__(self):
        return self.user.username

From views.py :

class UserProfile(LoginRequiredMixin, CreateView):
    def get(self, request, *args, **kwargs):
        username = self.kwargs['username']
        user_profile = ProfileModel.objects.filter(user=User.objects.get(username=username))
        gigs = Gig.objects.filter(user__username=username, status=True)
        print(user_profile.values())
        return render(request, 'jobexpertapp/profile.html', {'user_profile': user_profile, 'gigs': gigs,
                                                             'name': username})

From templates/profile.html :

{% if name == user.username %}
    #, In this case, I will add a, `edit` button and display other 
     info
    # the info in this case id displaying correctly
{% else %}
    # Here I need to display other user's info e.g
    <h1> {{ user_profile.slogan }}</h1>

You've used filter instead of get in your query, so it returns a queryset. That's why first works, since it then gets the first result for the queryset.

Use get :

user_profile = ProfileModel.objects.get(user=User.objects.get(username=username))

Note, this is more simply spelled:

user_profile = ProfileModel.objects.get(user__username=username)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM