如何添加链接到个人资料? Django 2.1.5

时间:2019-01-13 07:50:46

标签: python django

我有url,但是有错误。 例如,链接必须是example / profile / 3,但是模板重定向到example / profile / 4。 使用信号创建配置文件。我看到ID用户名和ID个人资料不匹配。也许是错误的。模板重定向到ID为“ User”的链接,但不重定向为ID“ Profile”的链接! 请帮助我。

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, blank=True, default='')
    last_name = models.CharField(max_length=30, blank=True, default='')
    location = models.CharField(max_length=30, blank=True, default='')
    #other fields

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

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


class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    #other fields    

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

signals.py

@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()

admin.py

class ProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'first_name', 'last_name', 'location', 'about_me', 'contacts')

admin.site.register(Profile, ProfileAdmin)

views.py

class PostCreateView(FormView):
    form_class = PostForm
    template_name = 'post/post_form.html'
    success_url = reverse_lazy('posts')

    def form_valid(self, form):
        response = super(PostCreateView, self).form_valid(form)
        form.instance.user = self.request.user
        form.save()
        return response

class PostDetailView(generic.DetailView):
    model = Post

当前 urls.py

url(r'^profile/(?P<pk>\d+)$', views.ProfileDetailView.as_view(), name='profile-detail'),

post_detail.html

{% extends "base_generic.html" %}
{% block content %}
<p><strong>Author:</strong> <a href="{% url 'profile-detail' post.user.pk %}">{{ post.user }}</a></p>
<p><strong>Description:</strong></p>
<p>{{ post.body|safe }}</p>
...

1 个答案:

答案 0 :(得分:0)

我认为您需要做的更改很少,例如:

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

您不需要此信号。由于User和Profile已通过OneToOne连接,因此它们是单独的实例。如果您更新user,则也不需要更新profile

此外,您所遇到的问题是您被重定向到错误的个人资料。我认为问题是您在此处通过url传递了错误的主键。您正在寻找个人资料,但您正在传递用户ID。因此,您需要像这样进行更改:

<p><strong>Author:</strong> <a href="{% url 'profile-detail' post.user.profile.pk %}">{{ post.user }}</a></p>

您应该能够从profile访问user.profile。有关更多详细信息,请在{strong> OneToOne 字段中查看docs