I'm doing project using Django and now I am trying to adapt js into the project. I'm not familiar with js and I'm wondering how I can manipulate db using js. For example, I want to use js for creating delete function. Currently, when I push delete button, I jump into the other page and then I have to push delete button again. But what I want to do is push the delete button and then pop up the window to confirm and delete something. How can I adapt js into Django in general?
Here is current way
first I have to push the button and jump into another page
<button style="display: inline;" onclick="window.location='{% url 'blog:delete_entry' entry_id=entry.id %}'" class="btn btn-link">Delete</button>
and then I have to push a button on the other page again.
<button type="submit" class="btn btn-outline-danger" id="delete-button">Delete</button>
Here is views.py
def delete_entry(request, entry_id):
entry = Entry.objects.get(id=entry_id)
if request.method != 'POST':
form = EditEntryForm(instance=entry)
else:
form = EditEntryForm(instance=entry)
entry.delete()
return HttpResponseRedirect(reverse_lazy ('blog:my_entry'))
return render(request, 'blog/delete_entry.html', {'entry': entry, 'form': form})
Anyone who can give me tips?
I could be wrong, but I typically only use javascript for the front-end. You are doing the back-end in Python with the Django frame work... it would be foolish not to use Python to manipulate the DB. Here is a template for mysql although I used Flask...
https://github.com/rootVIII/flask_mysql_template/blob/master/template.py
Even though it's Flask and not Django, the idea is still the same.
Your button should (or any form button) should have a Django endpoint associated with it (basically a path to the Django function). That way when the button is pressed, the Django/Python code on the back-end is ran. There you can perform your logic and database business in the Python code on the back-end.
Sorry for the Flask examples... but here is an endpoint for Flask in the index.html file from the above link... notice how the form action is associated with an endpoint /login_register
/login_register is what is ran when the form input button is pressed. It is a function on the back-end... in your case it might be named delete_entry
<form action = /login_register method="POST" id="userform">
<fieldset>
<!-- some labels and input values here -->
<input type="submit" name="submit" value="login/register" id="submit"/><br>
</fieldset>
</form>
So basically what I'm saying is that your button should not call Javascript. It should call a Python function on the back-end. And no you do not need to make a whole rest API to do this as was mentioned above
Related
If this form submits as invalid, I want to override the htmx and do a HttpRedirectResponse that refreshes the full page instead of just changing the div, #superdiv, contents.
<form id="create_form" action="." method="post" hx-post="." hx-target="#superdiv" hx swap="outerHTML">
{{ form }}
<button id="button" type="submit">Create</button>
</form>
I have been attempting to do this in the def post of my views.
if form.is_valid():
return self.form_valid(form)
else:
return HttpResponseRedirect(reverse_lazy("logs:manager_form"))
Would this be achieved better using JavaScript? I am trying my best to sticking to learning only vanilla JavaScript for now.
Thanks for any help.
I don't know if you already use it but the django-htmx extension is really good and handy.
You can trigger an entire client refresh from your Django view.
HttpResponseClientRefresh
I hope it is useful 😊
Use case (Django Project):
I want to log in on my login page -> Therefore I use this form in html (login.html):
<form class="loginform" action="" method="POST">
{% csrf_token %}
<div class="loginform">
{{form.as_p}}
</div>
<br>
<input type="submit" class="btn btn-success loginbtn" value="Login">
</form>
In case of successful log in I will redirect with DJANGO to this URL (localhost/welcome/)-> welcome.html:
LOGIN_REDIRECT_URL = "welcome"
I am able to send javascript notifications with alertify, but only when using simple things such as
click on it or mouseover:
function notification(text) {
console.log(text)
alertify.success(text);
}
I tried it with onsubmit="javascript:notification("")" in the html form tag, however this will
be displayed only BEFORE the URL redirection.
So my question is:
How is it possible to activate /send the push notification AFTER the URL redirection and in
case of successfull POST/ Log in?
I really appreciate your help! Thank you a lot!!
Javascript is client-side. That means your alertify.success(text); will be executed client-side, once server already did his render process.
The authentication process is server-side. So you have to make your server make your alertify a part of the rendered content.
Knowing that, you just have to change your LOGIN_REDIRECT_URL content page to include in it a call to notification:
<!-- your html template comes here -->
<script type="text/javascript">
notification('You are now logged in');
</script>
Be remembered that the notification will then display each time the person visits this page. You may want either to redirect him again, or to introduce a variable in Django to avoid displaying it again.
My goal is to click an HTML button on my Django web page and this will execute a local python script.
I am creating a local web application as an interface to a project. This will not be hosted and will always just run on my local machine. My project is run with a python script (which carries out numerous tests specific to my project). All I need is for a button in my web interface to execute this script on my machine.
I have a template index.html where the whole web page is located. I presume I need to call some form of views function possibly when the button is pressed?
How to execute python code by django html button?
This question suggests:
def index(request):
if request.method == 'GET':
return render(request, 'yourapp/index.html', {'output': ''})
elif request.method == 'POST':
py_obj = mycode.test_code(10)
return render(request, 'yourapp/output.html', {'output': py_obj.a})
I tried this just as a test but nothing happened when I went to the URL (located in the appropriate views.py):
def runtest(request):
print("Hello World")
Popen(['gnome-terminal', '-e', 'echo "Hello World"'], stdout=PIPE)
return
However I don't quite understand if this achieves what I need it to, I am struggling to understand what the answer is suggesting.
Where in the Django framework can I specify a call to a local python script when a button is pressed?
(I have very limited experience with web applications, this is simply just meant to be a simple interface with some buttons to run tests)
You want to try to submit a form on the button click. You can then import the functions you want to run from the script and call them in your view. You then redirect to the same page.
I hope this helps!
index.html
<form method="post">
{% csrf_token %}
<button type="submit" name="run_script">Run script</button>
</form>
views.py
if request.method == 'POST' and 'run_script' in request.POST:
# import function to run
from path_to_script import function_to_run
# call function
function_to_run()
# return user to required page
return HttpResponseRedirect(reverse(app_name:view_name))
Adding to answer above. You can run the function in a different view completely:
<form method="post" action="{% url 'app:view/function' %}">
{% csrf_token %}
<button class="btn btn-danger btn-block btn-round">Perform task</button>
</form>
And render whatever template you want (same template will execute task but seem like nothing has happened). This is handy if you already have a 'POST' form handler.
I'm working on a liferay portlet.
What I want to do is opening a new jsp with sending to it a URL parameter coming from javascript variable. I thought about it and I found two ideas:
1)Send the js variable to the jsp using ajax and then create a render url in jsp with a parameter the value received from js. But how I send js variable to jsp I don't find a good example in the internet.
2)Build the render url in javascript using the received parameter and then redirect from the script itself to the new jsp file using the render url that I found. For this idea I posted this question Liferay portlet: redirect to an other jsp page from javascript but I didn't get solution for it yet.
Has someone a suggestion how I can achieve what I want using one of my ideas or may be an other idea?
I found finally a solution for this problem.
I added in the jsp page a hidden post form that contains just one input and posts to an action method like that:
<portlet:actionURL var="jsVarActionURL" name="jsVarAction"/>
<form:form name="JsVarModel" method="post" modelAttribute="JsVarModel" action="<%=jsVarActionURL.toString() %>">
<form:input id="jsVar" type="text" path="receivedMessage" style="display:none;"/>
<input id="submit" type="submit" value="Add" style="display:none;"></input>
</form:form>
So my want was to for certain condition in javascript I have to send a js variable to new jsp page and open it. So in the script when the condition is valid I set to the input #jsVar the javascript value and I make a virtual click button in the submit button with trigger function of jquery like that:
var jsToJsp="Hello jsp I'm a js variable"
if(/*condition*/)
{
$("#jsVar").val(jsToJsp);
$("#submit").trigger("click");
}
In the controller the action method will receive the value coming from the form input field then it will redirect it to a render method:
#RenderMapping(params={"action=displayPageRender"})
public ModelAndView openUserProfilPage(RenderRequest request,RenderResponse response,Model model)
{
ModelAndView modelAndView= new ModelAndView("display");
modelAndView.addObject("jsVar", request.getParameter("jsVar"));
return modelAndView;
}
#ActionMapping(value = "jsVarAction")
public void sessionKeyActionMethod(#ModelAttribute("JsVarModel")ActionReceiveModel jsVar,ActionRequest actionRequest, ActionResponse actionResponse,Model model)
{
actionResponse.setRenderParameter("jsVar", jsVar.getMessage());
actionResponse.setRenderParameter("action", "displayPageRender");
}
Then I can receive it in display.jsp with ${jsVar} and everything works fine.
Hi Stackoverflow community!
This marks a long time followers' first post! I have almost always found an answer to my seemingly impossible questions here, but the time has come, I rage-quitted google searching and decided to post here! All help is appreciated!
As a Django noob, I am currently struggling to design an app that contains only 2 types of URLs (think: appear.in) So basically, homepage at localhost/ has a form for folder name input and create folder button.
If localhost/FOLDER1/ does exist, the folder will be expanded, otherwise (i.e. localhost/NOTEXISTING/) it will redirect to home with a rendered HTML text input with value='NOTEXISTING'.
Supplementary Contents table provides details on ForeignKey(Folder)
My current urlpatters are:
url(r'(\w+)/$', ShowFolder), #Trying to capture the folder name
url(r'^$', Homepage), #Trying to capture blank URL -> home
views.py contains:
def Homepage(request):
t = get_template('home.html')
html=t.render(Context({'foldername': foldername}))
return HttpResponse(html)
def ShowFolder(request, foldername):
try:
folder = Folder.objects.get(name=foldername)
html=t.render(Context({'folder': folder }))
return HttpResponse(html)
except Folder.DoesNotExist:
t = get_template('home.html')
fradd = ("Folder not found, wanna create one?")
html=t.render(Context({'foldername': foldername}))
return HttpResponse(fradd + html)
HTML Form looks like this:
<form >
<b>Folder Name: </b>
<input type="text" name="FodlerName" value=" {{ foldername }} ">
<input type="button" id="btn" value="Create Folder" name="btn">
</form>
So what really halted my progress is my lack of knowledge on page redirection, and capturing submit events.
What I would like to right now is to get folder name from input, create a folder with that name and redirect to localhost/NEWFOLDER without any more URL modification in the process.
I have tried countless tutorials on forms and HTML examples with JS an JQuery, albeit without success.
Any help would be more than appreciated!
Thank you sincerely in advance!
I'm not entirely certain what view is supposed to be doing what here. But just getting the folder name from the form post is easy, via request.POST['FolderName'], assuming you're submitting the form with POST which you're not but should be.
And redirecting to that name is also simple, using the redirect shortcut:
from django.shortcuts import redirect
folder_name = request.POST['FolderName']
return redirect('ShowFolder', (folder_name,))