Home > OS >  Add new page function does not work as it should. How can I add new page? Django
Add new page function does not work as it should. How can I add new page? Django

Time:01-02

I am trying to create a Addpage function with the following features;

  • Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry.
  • When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message.
  • Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page.

VIEWS.PY

class AddPageForm(forms.Form):
    title = forms.CharField()
    content = forms.CharField(widget=forms.Textarea(
        attrs={
            "class": "form-control",
        })
    )

def add_page(request):
    if request.method == "POST":
        form = AddPageForm(request.POST)
        
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            entries = util.list_entries()
            for entry in entries:
                if title.upper() == entry.upper():
                    return render(request, "encyclopedia/errorpage.html")
                else:
                    return redirect('encyclopedia:entrypage', title=title)
            util.save_entry(title, content)
    else:
        return render(request, "encyclopedia/addpage.html", {
            "form": AddPageForm()
        })

URL.PY

app_name = "encyclopedia"

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

ADDPAGE.HTML

<h1>Add Page</h1>
        <form action="{% url 'encyclopedia:addpage' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Submit" >
        </form>
{% endblock %}

UTILS.PY

def save_entry(title, content):
    """
    Saves an encyclopedia entry, given its title and Markdown
    content. If an existing entry with the same title already exists,
    it is replaced.
    """
    filename = f"entries/{title}.md"
    if default_storage.exists(filename):
        default_storage.delete(filename)
    default_storage.save(filename, ContentFile(content))

def list_entries():
    """
    Returns a list of all names of encyclopedia entries.
    """
    _, filenames = default_storage.listdir("entries")
    return list(sorted(re.sub(r"\.md$", "", filename)
                for filename in filenames if filename.endswith(".md")))

LAYOUT.HTML

<div>
  <a href="{% url 'encyclopedia:addpage' %}">Create New Page</a>
</div>

The problem I am currently having is that when I click the ADD button and I enter a title that already exist e.g CSS, it is supposed to take me to the error page but instead it submits however what I type does not get saved to the entry/homepage.

The second problem is that, when I click the ADD button and I enter a title that is new (which is supposed to submit and save on my home page), it instead takes me to the error page.

Could you please point out what I am doing wrong?

CodePudding user response:

In your for loop it will only check the first item, and if that is not an existing entry, it will immediately redirect (it never gets to the 2nd item). Whereas you probably intended it to check all entries, and if it does not exist then add and redirect?

Eg. would this work better?

def add_page(request):
    if request.method == "POST":
        form = AddPageForm(request.POST)
        
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            entries = util.list_entries()
            for entry in entries:
                if title.upper() == entry.upper():
                    return render(request, "encyclopedia/errorpage.html")
            util.save_entry(title, content)
            return redirect('encyclopedia:entrypage', title=title)
    else:
        return render(request, "encyclopedia/addpage.html", {
            "form": AddPageForm()
        })
  • Related