Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: calling view function without url mapping

Tags:

django

How do I pass information from an HTML form to my Python code, without having to specify a url mapping? For example, the following code sends data from the form in my 'index.html' template, to the 'myview' mapping, which then calls the 'myview' view function, which finally renders the 'mypage' template...

index.html

<form method="get" action="{% url 'myview' %}">

urls.py

urlpatterns = patterns('',
url(r'^mypage/$', views.myview, name='myview'),
)

views.py

def myview(request):
    return render(request, 'myapp/mypage.html')

However, do I really have to have a url mapping for this? What if I do not want to reload another webpage, and I just want to stay in the same 'index.html' page?

I'm just a little confused over how views are actually called, in the case when I want the view to act more like a traditional function, to process some data, rather than to necessarily render a new template.

Thank you!

like image 879
Karnivaurus Avatar asked Mar 03 '14 15:03

Karnivaurus


1 Answers

You always need a URL if you want your browser to call a view. How else would the server know which view to call? The only way is through the URL mapping. Remember that there is no persistent relationship between the browser and the server: the only way they can communicate is through requests to URLs.

You don't always need to render a template, though. A view can return anything, including raw text or JSON.

I don't understand what you mean about not reloading another page. Posting data to the server is a request for another page: that's just how HTTP works. You can certainly choose to post to the same page you're currently on; and in fact that's exactly how forms are processed in the recommended Django pattern. But you still need a URL mapping pointing at that page, in order to get it in the first place as well as to process the submitted dat.

like image 169
Daniel Roseman Avatar answered Oct 02 '22 16:10

Daniel Roseman