Executing Function in Django Template with button OnClick - python

This is a filter in my Django Templates tag.
#register.filter('saving_bookmarks_db')
def saving_bookmarks_db(news_data,news_source,):
#this will save the data in db
In my Django Template, i have one button like this
<button data-toggle="modal" id="myClickButton" href="#dbModal" class="btn btn-info pull-right custom" >Bookmark</button>
this is my include command, which will include modal html and save the also save the data using tag
{% include "db_saving.html" with source=source data=data %}
All i want to do is that, this include command execute only when the button is click but in django whenever the page is refresh, it save all the data in the DB and not the one when i click the button.

You cannot do things like this in a template filter. That will always be executed on render.
Anything that affects the database in response to user action can only happen in a view, accessed via a URL. It sounds like you want that to be called from an Ajax function in your template which in turn is called from your onclick handler.

Related

Python, django, html: I made a booking form and I would like to set this page to login access only without inheriting 'LoginRequiredMixin'

In other words, user can not access this booking_form.html without login.
Booking
or
<button onclick="location.href='/booking_form/'">Booking</button>
If user hit the button, then they need to login first to access that page. if login successfully, then they would be on the page of booking_form automatically
This one has to be done without inheriting 'LoginRequiredMixin'...
try below code probably works in your HTML template.
{% if user.is_authenticated %}
Booking
{% else %}
your logic here
you can attach the login_required decorator to your login view
#login_required
def view_name(request):

Redirect back to previous page after login in django-allauth

There is a button in blog detail view that asks user to login to comment, but after login user is redirected to home page because in settings.py I declared:
LOGIN_REDIRECT_URL = "projects:home"
I searched and I found this could be a solution:
Please login to reply
but this even didn't work.
Thank You
You are half-way there: When you add ?next={{request.path}} to your a tag, you are creating a 'next' variable and assigning the current path to it. But that alone isn't enough for your desired result; you still need to actually use that variable in your login form.
You haven't shown us your login template, but I assume it's a basic form. Add a hidden button to the login form, and have it use the 'next' variable that was captured in your a tag. Put the following code inside your login form tag, after everything else, but before closing the the form:
<input type="hidden" name="next" value="{{ request.GET.next }}" />
When a user submits the Login form, the template will use the value stored in request.GET.next, which was captured from your a tag.

Button not executing Django/Python script

In my home.html template:
<button type="button" class="btn btn-dark"
method = 'GET' action = '/action_name/' name="audio_record">Record Audio</button>
In my views.py:
def audio_functions(request):
print('called function')
In my urls.py:
path('/action_name/', views.audio_functions, name='audio-record'),
what am i doing wrong?
Edit: I replaced the button with the suggested version below:
<a href="{% url 'audio-record' %}" class="btn btn-dark"
>Record Audio</a>
But I have a new problem. I actually don't want to redirect to by url/action_name. I just want to trigger the python script within the browser. How can I do this?
in html :
<a href="{% url 'audio-record' %}" class="btn btn-dark"
>Record Audio</a>
and urls.py
path('action_name', views.audio_functions, name='audio-record'),
In your urls.py you do not need the leading forward slash, as django adds this in automatically. Replace it with this and it should work:
path('action_name/', views.audio_functions, name='audio-record'),
Also the method and action attribues would normally go in the <form> tag, and not the button one. Also change type to submit on your button.
As #SALAHEDDINEELGHARBI says, you should really be using {% url 'audio-record' %} rather than hard-coding the url, however this is not the problem in this case (you shouldn't have a leading slash in urls as this would leave to a url with a double slash)
EDIT - In response to your edit:
You can't trigger a python script within the browser. It's a common misconception. Django is a web framework built in python, yes. But anything that happens in the browse has to happen in javascript. If you want to use python, you'll need to make a call to some django endpoint, do the python, and the send it back.

Accessing model data in Django template

I am using the below lines to pass data to my template index.html, model1 being the class in my models.py.
data = model1.objects.all()
return TemplateResponse(request, 'index.html', {'data': data})
I am able to access data on the front end by using a for loop as shown below
{% for x in data %}
<h3>{{x.name}}</h3>
<h4>{{x.department}}</h4>
{% endfor %}
Since there are mutliple objects in this data, my question is if I want to access only the department of particular object with certain name, how can I do that?
For example here I am using a for loop, consider there are two objects in the data. Then the output would be
name1
department1
name2
department2
So now if I need to access only name2 without any loop, how can i do that?
Updating the question: I am updating this question with html, so that the question looks clear.
table id="example" class="table table-striped" cellspacing="1" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>View/Edit</th>
</tr>
</thead>
<tbody>
{% for x in data %}
<tr>
<td>{{x.id}}</td>
<td>{{x.name}}</td>
<td>{{x.department}}</td>
<td>View</td>
<button type="button" class="btn-sm btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
view</button></td>
</tr>
{% endfor %}
</tbody>
This is how my html looks, I am using data-table here. So all the data is captured in a table automatically. As you can see every row has a view button that I would implement. Once the user clicks the view button, I should pop up a modal dialog to show all the other details like {{x.dateJoined}} etc which I don't show in the table. But if I use a separate view to pop this dialog, I should send a request to the view from my template saying which row(with some ID) the user has clicked. How can i achieve that? How can I bind the view button with respective rows here?
You need to write custom template tag which will take the queryset and filtering parameters and returns you appropriate object, you can use simple_tag:
myapp/templatetags/myapp_tags.py
from django import template
register = template.Library()
#register.simple_tag
def get_model1_object(queryset, **filters):
if not filters:
raise template.TemplateSyntaxError('`get_model1_object` tag requires filters.')
retrun queryset.filter(**filters).first()
Then in template:
{% load get_model1_object from myapp_tags %}
{% get_model1_object data name='blah' as obj %}
Note: Your filtering criteria might yield multiple results but in get_model1_object i am only returning the first object assuming your criteria will be strict, change it according to your needs.
The first thing to understand is that template rendering happens on the server, before the user sees anything in their browser. The template is not sent to the user, only the HTML that the template generated. When the user is interacting with the page, the original template is not involved. So, you have two choices here:
You can render the data for all the objects in hidden div's on your page, then use javascript with something like a jquery dialog to display them on demand. This is only realistic if you have very few records.
You can create a second view with its own template, which renders just the HTML for the modal dialog contents. You could then, again using javascript/jquery, make an AJAX request to load the contents of the dialog that you need when you need it. In your first view template, the list of departments, include the url of the object you want to fetch, eg:
{% for x in data %}
<tr>
<td>{{x.name}}</td>
<td><a class="deptlink" href="{% url 'dept_detail' x.pk %}">
{{ x.department }}</a></td>
</tr>
{% endfor %}
Where dept_detail is the name of the urls.py entry for your view that supplies the contents of the dialog.
Then in your javascript, hook the a tag so it opens your dialog instead of leaving the page:
$('.deptlink').click(function (event) {
event.preventDefault();
# then the code after this is up to you, but something that'll
# load the url into your dialog and open it.
$('yourdialog').load($(event.target).attr('href'));
Since you say you are an intermediate in javascript I won't get into the details of implementation, but basically, the moral of the story is that the output of django is going to be an HTML page. Anything that you need to have on the client side either has to be in that page, or you will have to make another request to the server to get it... Either way, you'll need some javascript to do this, since you want a modal dialog with client side interaction.

Open page in Django using <button> instead of <a>

I am creating my first Django app, and I am trying to open a template using a button tag. I have something like this here:
<button type="submit" onClick="window.location.href='details'">View</button>
In my urls.py, I have:
url(r'^details/$', TemplateView.as_view(template_name='details.html'), name=""),
I am not sure how to set the URL in urls.py to be able to access the details.html page. Currently, the page does not open. Does someone know how I can open it please?
If you have type="submit", sounds like you are using a form, right? If you do have a form, your url shouldn't be on the button but on the form action attribute.
You need to give your url a name, like:
url(r'^details/$', TemplateView.as_view(template_name='details.html'), name="details"),
Then your action would be:
action="{% url 'details' %}"
Read some resource online to learn how to use a form action.
I suggest you learn some html basics before jumping into django development, it would save your time wondering these kind of questions.
If you are not using a form, you might just need an <a> tag that looks like a button with css decoration. If you are using bootstrap, check out .btn class in the documentation.
It would be better to avoid javascript and just make a really simple form:
<form method="GET" action="{% url 'details_page' %}">
<button type="submit">View</button>
</form>
But you also need to name the route like so:
url(r'^details/$', TemplateView.as_view(template_name='details.html'), name="details_page")
Links are still preferrable though. It would be better to use some sort of CSS to make links and buttons look the same so you can use them interchangeably like bootstrap.

Categories

Resources