[Answered ]-Proper way of using url patterns

1👍

At the end of your createItem function, you are rendering HTML of the page rather than redirecting. Instead, you need to do

return HttpResponseRedirect(reverse('kar:index'))

You will need to import HttpResponseRedirect and reverse which is used to resolve the URL through its name.

Check this out: https://docs.djangoproject.com/en/1.10/topics/forms/#the-view

👤zubhav

1👍

What I’d like to do is after createItem is run, it should send the
user back to homepage/CMS/ and not homepage/CMS/createItem. Would that
be the proper way to do it? Or is there a smart way of doing this.

That would indeed be the proper and smart way to do it. Have one view handle both GET and POST and then redirect after successful form submission. This ensures that the user can’t resubmit the form merely by refreshing. And you address your concern about repeating your code.

urlpatterns = [
    url(r'(?i)^$', views.index, name='index'),
    url(r'^createItem/$', views.createItem, name='createItem')
]

Then combine your views

def createItem(request):       
    if request.method == 'POST':
         f = itemCreateForm(request.POST)

         if f.is_valid():
             f.save()
             return HttpResponseRedirect('/homepage/CMS/')
    else :
         form = itemCreateForm()

         context = {
              'form' : form,
              'message' : 'Content Manage Site'
         }
    return render(request, 'CMS.html', context)

Note that the code is now shorter, it gives proper feedback to the user when the form is not valid. And you can’t refresh to submit the for twice. We need a small change to the template

<div class='newItemFields'>
    <form action=method="POST">
    {% csrf_token %}
        {{ form.as_p }}
        <input type="submit">
    </form>
</div>

The message display part isn’t needed anymore

👤e4c5

Leave a comment