0👍
The main issue is that you allow the name field to be blank and null, thus when you ask for it in the url of your <a href>
it is sending in an empty string, yet your userProfile
view is asking for a pk
.
First, remove the null and blank from your classes:
class Project(models.Model):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200, blank=True, null=True)
Second, require users to login before they enter, otherwise you will still have blank strings for the project.owner
, which will lead to the same result. You can do this with the @login_required
decorator:
from django.contrib.auth.decorators import login_required
@login_required
def projects(request):
projects = Project.objects.all()
context = {'projects':projects}
return render(request, 'projects/projects.html', context)
Then in your html:
<a class="project__author" href="{% url 'user-profile' project.owner.user.pk %}">
But finally, the below
answer by @Snow is correct. The User
model already has a username, first_name, last_name field, so you might be able to get rid of the name field in the Profile model, then do just:
<a class="project__author" href="{% url 'user-profile' request.user.pk %}">
1👍
The User object, already has fields for basic information like the username
, password
, email
and first
and last
name.
You’re creating a new field called name to do URL lookups, but have set your field name to blank=True
. You can’t lookup a profile without having a slug
(in your case the profile name). So instead, you should lookup the user by the username. Always try to stick to the DRY approach (don’t reinvent the wheel).
Try doing this:
<a class="project__author" href="{% url 'user-profile' project.owner.user.username %}">
if you have an app_name in your urls, then you need to use the app name.
<a class="project__author" href="{% url '<app_name>:user-profile' project.owner.user.username %}">
- [Answered ]-Django: Best way to join data from multiple, associate models
- [Answered ]-Django filter dynamic field name based on queryset
- [Answered ]-How to add extra columns for a model if in particular category in Django + Postgres
- [Answered ]-Send data array (same key values) using php curl
- [Answered ]-How do I use Docker on BitBucket pipelines to test a Django app that needs PostGIS?