简体   繁体   中英

How can I get the user profile detail to work properly in django

I am trying to include a profile feature in a simple blog site. I have created a profile model using the one to one link for the user field, also created a function view for the profile detail with corresponding template name but i keep getting a 404 error.

    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
    username = models.CharField(max_length=15, default='Anonymous')
    dp = models.ImageField(null=True)
    country = models.CharField(max_length=20, null=True)
    age = models.IntegerField(null=True)
    joined = models.DateTimeField( auto_now_add=True)

    class Meta:
        ordering = ['joined']

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('profile_detail',  args=[str(self.id)])


@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
def profile_detail(request, pk):
    user = get_object_or_404(User, pk=pk)
    context = {'user': user}
    return render(request, 'milk/profile_detail.html', context)


profile_detail.html
{% extends 'milk/base.html' %}
{% block title %}
{% endblock %}
{% block content %}
<h2>{{ user.get_full_name }}</h2>
<ul>
  <li>Username: {{ user.username }}</li>
  <li>Location: {{ user.profile.country }}</li>
  <li>Age: {{ user.profile.age }}</li>
</ul>
{% endblock %}


template referencing

                <a href="{% url 'post_detail' pk"><em>{{user.get_username }}</em></a>

urls.py

    path('profile/<int:pk>/', views.profile_detail, name='profile_detail'),

you can display current user info like this without passing through context

{% extends 'milk/base.html' %}
{% block title %}
{% endblock %}
{% block content %}
<h2>{{ request.user.profile.get_full_name }}</h2>
<ul>
  <li>Username: {{ request.user }}</li>
  <li>Location: {{ request.user.profile.profile.country }}</li>
  <li>Age: {{ request.user.profile.profile.age }}</li>
</ul>
{% endblock %}

or instead of 'get_object_or_404' try

user = User.objects.get(id=pk)

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