Calling a function from HTML to Python file - python

I have a index.html page with a list of "cards", where each card have a "Click to Select" link.
When user click in this link i'd like to call a function in python to select this item, see:
def selectItem(request, item):
#so something with this item
so, in my html pagE:
<div class="card-action">
Selecionar
</div>
This don't work. What is the right way to do it ?

You can not call a function like that. A browser requests data with an HTTP request, and the server answers with an (HTTP) response. Such requests have a URL, and Django can route the request - with the URL - to the right view that will calculate a response.
We thus need to construct a view that can then be called. Your call is already quite close:
# app/views.py
from django.http import HttpResponse
def select_item(request, item_id):
# so something with this item_id
# ...
return HttpResponse()
Since most objects are not serializable (and usually you do not want that anyway, since it would expose a lot of (potentially sensitive) data to the user, we thus need to work with an id (an identifier that is for example stored in the database that corresponds to an object).
The response contains the data in the response. Frequently that is HTML code that is then rendered by the browser.
Now in urls.py, we can specify how the url looks like, for example:
# app/urls.py
from django.urls import path
from app.views import select_item
urlpatterns = [
path('select_item/<int:item_id>/', select_item, name='select_item_view'),
# ...
]
The urlpatterns need to be included in the root urlpatterns (in the project root).
Now in the HTML template, we can generate the URL that matches with this view, something similar to:
<div class="card-action">
Selecionar
</div>
Django will then make sure that the href points to an URL that refers to the select_item view with the correct parameter.

Related

How to execute script python when i click button in form html?

hello how can i run script that i build on python when i click button on form html
i saw examples like this but i dont get it:
Html code: index.html
<form action="{% url my_view %}" method="post">
<input type="submit" value="Ok">
</form>
views.py
import django.shortcuts import render
def my_view(request):
if request.method == 'POST':
import set_gpio
#my url is "templates/load.py"
return #How can i return?
You need to return an HttpResponse object from your view. You can return one response inside your if statement, and another outside of it (so anything but a POST). Usually the render shortcut is used to render a response from a template. So your view would be something like:
import django.shortcuts import render
def my_view(request):
if request.method == 'POST':
# The user clicked the button (POST)
return render(request, "load.html")
# The user is just loading the view for the first time (GET)
return render(request, "index.html")
I highly suggest going through the django tutorial.
You have to realise that Django is a HTTP based framework meaning that when an HTTP request is sent to a url, Django will be allowed to perform an action. So, every function is actually a reaction to the HTTP requests that the user sends to your urls.
Also, if you are using Django template system, the html file should be rendered by Django in the first place. So, you cannot have a standalone html file with {% url my_view %} in it.
First, you have to configure the main urls.py which is in a folder with the same name as your project.
Second, in your app, create an urls.py file and configure it.
At the end, you connect your my_view to a specific or set of urls and will be triggered when a request is sent to that url, whether GET or POST.
These are somewhat large (and easy) topics for which you have to watch a tutorial or read the Django documentations.

Django html interacts with views

I have a html that contains some forms and buttons. One button corresponds to a file that I have uploaded. I want to achieve when I click on a button, my views will act on the corresponding file, and shows the results in another html like picture below.
How can I give each button specific parameters from my models? and how to get the parameter in my views.
I tried this code, but failed to get it. is this right?
<button type="submit" class="btn btn-info btn-xs" name={{item.description}}></button>
You must do something like that:
You should add new route for your new page to routes.py:
from . import views
urlpatterns = [
...
url(r'^new-page/$', views.new_page_view, 'new_page'),
]
after that your views.py must have your view function, that will execute when you go to url /new-page/
views.py:
from django.shortcuts import render
def new_page_view(request, question_id):
return render(request, 'path/to/your/template')
You can read more about render() there
In your template (When you want to add your link button) you must add following string:
Link to new Page
Something loke that you must do with your project.
More about this you can read there
I hope this answer will help you

django-contact-form how to use the form inside any template, without a new url?

I have installed django-contact-form, and the default url to the form is 'contact/'. But, I already have my own contact page, let's call it 'contact_us/', I wish to include the form inside 'contact_us/', using the url and view I already have for 'contact_us/'.
The usual way to do that is by using {% extends 'contact_us' %}, but if I do this, and remove my original 'contact_us/' url, it gives me an ReverseError.
The way I think that would be possible is if sent the ContactFormView (from django-contact-form) as context to 'contact_us/', but I think that's not possible because each view has it's own url.
I want to know a way to be able to put the form easily inside of any template. There's probably a simple way to do that and I don't know.
You can call the ContactFormView from the contact_us by:
1. By overriding the url
urls.py
from contact_form.views import ContactFormView
from django.views.generic import TemplateView
urlpatterns = [
# ... other URL patterns for your site ...
url(r'^contact_us/$',
ContactFormView.as_view(),
name='contact_form'),
url(r'^contact_us/sent/$',
TemplateView.as_view(template_name='contact_form/contact_form_sent.html'),
name='contact_form_sent'),
]
2. If you want to customize this view
In views.py
from contact_form.views import ContactFormView
class CustomContactFormView(ContactFormView):
# Customize any function that you want to
template_name = 'custom_template.html'
urls.py
from views import CustomContactFormView
urlpatterns = [
# ... other URL patterns for your site ...
url(r'^contact_us/$',
CustomContactFormView.as_view(),
name='contact_form'),
]

Django/Python: How to create redirect from one view/url to another?

Django 1.8 / Python 3.4
I have a website.html that displays entries from my database, each of which is identified by its ID. Now, at the end of each displayed entry I have a link to an "edit" view, looking like this:
<td>edit</td>
The link is working fine and leads to the correct view:
def edit(request, object_id):
implemented in views.py. There some code is executed correctly too, and in the view's last line I have:
return redirect('website.html')
Obviously, after the chosen entry has been edited I want my website.html with the edited entry being displayed in the browser again: 127.0.0.1:8000/website/. However, what happens is that I get a Page not found (404) error, with the information:
Requested URL 127.0.0.1:8000/website/2/website.html
The "2" here is the ID of the entry.
Maybe I have the wrong idea about how redirects work, but I was assuming that instead of calling the respective view's url from url.py it would open the url provided in the redirect() function?!
What happens, though, is that this url gets appended to the view's url!
Here is my urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from www.list.views import website, edit
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^website/$', website, name="website"),
url(r'^website/(?P<object_id>\d+)/$', edit, name="edit"),
]
I'm pretty sure the third url entry is causing the problem but I have absolutely no idea how to change it for the redirect to work. Also, the edit view doesn't have an actual website (template), but I'm supposed to provide a URL for it, so this was the best I could think of.
The way this should work is: Click the "edit" link on website.html, the code from the edit-view is being executed, and, afterwards, the website.html with the change in the database entry gets displayed again.
^^ How to achieve this? Any help is appreciated!
Redirect uses names or absolute URLS. You should either use the name of your URL:
return redirect('website') # since name="website"
or an absolute URL, like:
return redirect('/website/')
you can use the reverse function instead of redirect
from django.core.urlresolvers import reverse
return reverse('website')
I found the mistake and the solution:
At the end of the edit-view it's correct to write "return redirect('website')". However, just as I assumed, the URL of edit in urls.py was wrong.
Instead of
url(r'^website/(?P<object_id>\d+)/$', edit, name="edit"),
it should just be
url(r'^(?P<object_id>\d+)/$', edit, name="edit"),
Thank you nonetheless!

Redirection is leading me to Page not found error in Django

Project urls.py includes app urls. I am using HttpResponseRedirect to get Likes posted on site. I am not trying to call for template so this is why not using render_to_response. My app view is:
def like_article(request, article_id):
if article_id:
a = Article.objects.get(id=article_id)
count = a.likes
count += 1
a.likes = count
a.save()
return HttpResponseRedirect('articles/get/%s' % article_id)
My app urls.py reflects likes redirection like this:
url(r'^like/(?P<article_id>\d+)/$', 'article.views.like_article'),
My parent "articles" HTML file extended from base says:
<p>{{article.likes}} people liked this article</p>
My single article page extended from base.html shows:
<p>Like</p>
Please advise.
You'd better use {% url [name] [parameters] %} in your template while reverse function in your view to create urls.
In your question, I think the problem is the url router doesn't match.
See:
<p>Like</p>
And:
url(r'^like/(?P<article_id>\d+)/$', 'article.views.like_article'),
It seemed the /article prefix doesn't appeared in you url.
Have you mapped the url - articles/get/article_id, i.,e added a similar pattern in urlpatterns (ex: url(r'^get/(?P<article_id>\d+)/$', 'article.views.get_article', name='get_article'),) tuple, to which you redirected the users!
If yes, then have you created a proper view for it!

Categories