Clayton Horning
Clayton Horning

Reputation: 238

Trying to edit post: Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/edit/(?P<pk>[0-9]+)$']

I am trying to be able to edit the question with an tag which references my edit_post function in my views.py. I think the issue is because I haven't passed in the context into the right view for it to be displayed but I am not sure how to fix it. Getting this error - Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P[^/]+)/edit/(?P[0-9]+)$']

Views.py

@login_required(login_url='sign_in')
def dashboard(request, *args, **kwargs):

    username = request.user.username

    filtered_questions = Question.objects.filter(user_id=username)

    context = {
    'filtered_questions': filtered_questions,
    }

    return render(request, 'users/dashboard.html', context)

def edit_post(request, pk):
    question = Question.objects.get(pk=pk)
    if rerquest.method == 'POST':
        form = QuestionForm(request.POST, instance=question)
        if form.is_valid():
            form.save()
            question.user = request.user
        
            return redirect('/')
        else:
            form = QuestionForm(instance=question) 
    else:
        form = QuestionForm(instance=question)

    context = {
        'form': form,
        'question': question,
    }

    return render(request, 'users/edit_question.html', context)

Urls.py

urlpatterns = [
    path('<username>', views.dashboard, name='dashboard'),
    path('<username>/upload', views.upload, name='upload'),
    path('<username>/edit/<int:pk>', views.edit_post, name='edit')
]

Template with the edit question button

<a href="{% url 'edit' question.pk %}">

Edit:

context = {
    'filtered_questions': filtered_questions,
    'username':username,
}

Tried to pass username in as context variable and render it in template like so

 <a href="{% url 'edit' username question.pk %}">

Upvotes: 0

Views: 592

Answers (1)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

You have to give username too for url to match:

<a href="{% url 'edit' username=user.username pk=question.pk %}">

You don't have to pass username from context if you are passing request.user.username. Coz, user is always accessible from authenticated page from template.

Upvotes: 1

Related Questions