Home > Back-end >  NoReverseMatch at /projects/ Reverse for 'user-profile' with arguments '(''
NoReverseMatch at /projects/ Reverse for 'user-profile' with arguments '(''

Time:03-13

I am just getting started with Django and I don´t know exactly where this error comes form. It´s probably related to the owner attribute. Here is my code so far.

projects/modely.py

class Project(models.Model):
    owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)
    title = models.CharField(max_length=200)
    

users/models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, blank=True, null=True)
    

projects/views.py

def projects(request):
    projects = Project.objects.all()
    context = {'projects':projects}
    return render(request, 'projects/projects.html', context)

projects.html

{% for project in projects %}
<p><a  href="{% url 'user-profile' project.owner.name %}">{{project.owner.name}}</a></p>
{% endfor %}

users/views.py

def userProfile(request, pk):
    profile = Profile.objects.get(id=pk)
    context = {'profile':profile}
    return render(request, 'users/user-profile.html', context)

CodePudding user response:

I'd need to see your urls.py for a better answer, but the 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.

Try this:

<a  href="{% url 'user-profile' project.owner %}">

CodePudding user response:

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  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  href="{% url '<app_name>:user-profile' project.owner.user.username %}">
  • Related