How to make edit function work in views.py Django

Viewed 105

I am creating an edit option for my entry. But instead of redirecting to the entry page, it is taking me to the addpage to create a new form. How do I redirect to the edit page?

Also, how do I make sure that the users previous input would reflect when they click on the edit button. I used initials - is this the best way to do it since I'm not using models but rather forms.Form.

VIEWS.PY

class AddPageForm(forms.Form):
    title = forms.CharField(max_length=20)
    content = forms.CharField(widget=forms.Textarea(
        attrs={
            "class": "form-control",
            "placeholder": "Tell us more!"
        })
    
def edit_page(request, title):
    entry = util.get_entry(title)
    if request.method == "POST":
        form = AddPageForm(request.POST, initial={
                "title": title,
                "content": content
                })
        
        if form.is_valid():
            util.save_entry(title, content)
            return redirect('encyclopedia:entrypage', title=title)

    else:
        form = AddPageForm()
        return render(request, "encyclopedia/editpage.html", {"form":form})

EDIT PAGE

{% block body %}

    <h1>Edit {{ title }}</h1>

    <form action="" method="post">
        {% csrf_token %}
        {% form %}
        <input type="submit" value="Submit" class="btn btn-secondary">
    </form>

ENTRY PAGE

{% block body %}
        {{ content|safe }}

        <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a>
        <!-- <input="text" name="title" value="{{game.title}}" />
        <input="text" name="genre" value="{{game.genre}}" /> -->

{% endblock %}

URLS.PY

app_name = "encyclopedia"

urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.entry_page, name="entrypage"),
    path("search", views.search, name="search"),
    path("add_page", views.add_page, name="addpage"),
    path("edit_page/<str:title>", views.edit_page, name="editpage")

]
1 Answers

I think the issue with your code is that it is calling a redirect on a url that doesn't exist. 'encyclopedia:entrypage' does not exist in your urls.py. There are two ways of fixing this. Option #1 Create a url for entry page in urls.py with name=entrypage and a parameter in the url denoting which entrypage. Or option #2 Return directly to the entrypage view in the edit_page function. Here's a rough sketch of how you would do that

In edit_page in views.py:

# ...Code above

if form.is_valid():
    util.save_entry(title, content)
    return entry_page_view(request, title) 
    # 'title' if this view has a title passed as a kwarg or arg

# Code below...
Related