Home > other >  Django Form does not display, gives error that it is unable to match urls
Django Form does not display, gives error that it is unable to match urls

Time:11-07

With Django, I am trying to display a form to edit content on a page. However I run into the following error when trying to visit the editpage view

NoReverseMatch at /editpage/CSS/ Reverse for 'editpage' with keyword arguments '{'topic': ''}' not found. 1 pattern(s) tried: ['editpage\/(?P[^/] )\/$']

Where "CSS" here is an example pulled from the link address via str:topic in urls.py.

I think the issue is with my form action in editpage.html, where I reference the editpage url and I have tried numerous combinations but am unable to get it to display. Removing the form allows the link to display with no error. Any help is much appreciated.

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("editpage/<str:topic>/", views.editpage, name="editpage"),
]

editpage.html

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Edit Page
{% endblock %}

{% block body %}
    <h1>Edit page</h1>

    <form action="{% url 'editpage' topic=topic %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="submit">    
    </form>

{% endblock %}

views.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django import forms
from . import util

class EditPageForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'topic', 'class': 'form-control'}))
    article = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Existing article', 'class': 'form-control'}))

def editpage(request, topic):  
    return render(request, "encyclopedia/editpage.html", {"form": EditPageForm()
    })

Thank you in advance!

CodePudding user response:

Try this.the problem is that you have forgotten to pass the topic inside the context and from what i see you are not handling correctly the form(you have to make a GET and POST to handle the form).if you need more help about this let me know.

def editpage(request, topic):  
    return render(request, "encyclopedia/editpage.html", {"form": EditPageForm(),"topic":topic})
  • Related