I have django form with name and email address as a form field in forms.py file.
I am implementing that form in HTML Page with the help of {form.as_p}.
Now I have JavaScript inside that same HTML page with...
{% block javascript %}
<script>
</script>
{% endblock %}
Now How can I access both form variable inside this script tag. I want to validate data at client-side and than wants to send at server.
Will getElementById() method works? and If so what I need to write for access my form variables or any other good alternative.
Thanks
Yes, its possible. Django gives an id in format id_fieldname to each field you define in your Django form.
E.g. For name field, id in HTML will be id_name and For email_address field ,id in HTML will be id_email_address
Now you can simply use getElementById() in your JS with these ID for validation.
Related
I am using Flask and wtforms to create a web page "index.html" that loads multiple forms. The selection of forms that are rendered depend on dropdown selections, and a variable "serviceid" updated from an API call. The form selection and rendering is handled in an included file "form_select.html", which requires "serviceid" value to pick the correct form. I am having trouble figuring out how to refresh the forms based on updated serviceid values without doing a full page reload.
I can use something like this with jinja2 include to render "form_select.html" and pass the "serviceid" variable so the right form is rendered:
<div id="loadform"> {% include './form_select.html' with serviceid %} </div>
This is working on first load, but I need to select a new form when the user selects a new value from a dropdown. I am running a script based on mydropdown.onchange, which first obtains the correct "serviceid" value, but now I need to rerender just the loadform div with this value.
I have tried approaches along the lines of the following - but I cant seem to figure out how to deliver this jinja2 with .innerHTML.
document.getElementById('loadform').innerHTML = `
{% with serviceid=serviceid %}
{% include './form_blocks.html' %}
{% endwith %}
`;
There is probably a better way to do this, but the examples I can find don't include passing in a variable. Can I use innerHTML for this, or is there a better way?
I am using a javascript to send an html form to django.
js looks like this:
document.getElementById("fooform").submit();
and the html form looks like this:
<form class="form-inline" id="fooform" action ="{% url 'foo:doo' %}" method="post">
{% csrf_token %}
<input type="hidden" id="fooinput" value="" />
</form>
the js can write the data into the input field without any problems and also carry out the submit. my problem is using the crsf token.
I have already put the token {% csrf_token %} in every conceivable place. (Before the form, before the js...). in the html code is the token also correct.
django gives me the error:
Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function passes a request to the template's render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
Edit:
The view.py:
def foo_view(request):
print(request.POST)
urls.py:
app_name = 'foo'
urlpatterns = \
[
path('doo', views.foo_view, name='foo_view'),
]
I am new to OctoberCMS so I don't know a lot of things.
I read the October documentation and i know how to pass variables when using partials in the static way:
{% partial "location" city="Vancouver" country="Canada" %}
My problem is that I need to use php or js variables. Let's say I have an input field where the user writes an ID, then after a button is pressed I want to pass the ID to a partial. I am trying to do something like this :
{% partial "location" city=$city country=$country %}
Can someone help me? Thank you.
Have you tried this method as documented here? https://octobercms.com/docs/cms/partials#partial-variables
{% partial "location" city=city country=country %}
EDIT
As an aside, you need to define your page variables in the onStart function.
url = "/blah"
layout = "default"
==
<?
function onStart()
{
$this['country'] = ...;
$this['city'] = ...;
}
?>
==
{% partial "location" city=city country=country %}
EDIT
Have you read the section on AJAX? https://octobercms.com/docs/ajax/introduction
More specifically - https://octobercms.com/docs/ajax/update-partials#pushing-updates AND https://octobercms.com/docs/ajax/update-partials#update-definition
EDIT
Just re-read your original question and you're asking about binding to form elements, not AJAX.
Take a look at the JS API - https://octobercms.com/docs/ajax/javascript-api#javascript-api
I think you could do something like:
<form onsubmit="$(this).request('onMyProcessingMethod'); return false;">
$('form').request('onMyProcessingMethod', {
update: {myPartialName: '.whereIWantTheOutputToGo'},
data: {country: 'Canada'} // Not 100% sure how to access form input; maybe ID selector
})
You can use variables inside the partial in this way:
<p>Country: {{ country }}, city: {{ city }}.</p>
I currently have a JSP page that contains two forms:
<body>
<form id="1"></form>
<form id="2"></form>
</body>
Only one form will be showing at the time when viewing the page.
There is a JS validation file that is being used to check the form integrity when submit.
To simply put, this JS file cannot be changed. Whenever the JS file is being called, the core function takes in the form.
function validateForm(formToValidate){}
The validation result alert is a JSP page id="alertMessage", being hidden at the beginning by CSS:
#alertMessage {
display: none;
}
When any validation error happens, the page turns to visible by simple jQuery: $("#alertMessage").show();
The CSS requires the id="alertMessage" to not display the alert JSP page, and the JS requires the id="alertMessage" to do validation, and show alert messages.
Since I am having two forms in the page and the forms contain different content for validation, I have to include two JSP alerts in my page.
<body>
<jsp:include page="alert for form 1">
<form id="1"></form>
<jsp:include page="alert for form 2">
<form id="2"></form>
</body>
The issue:
Not only I am having duplicate ids id="alertMessage" in one page, it is always the first JSP alert page being picked. So even I am submitting form 2, the alert for form 1 will be triggered. Combing the alerts into one JSP alert page is not an option due to my design limitation.
How do I fix this?
These slight modifications should help you.
Pass the form id in the function validateForm(formToValidate) as formToValidate parameter.
Remove the id tag from the error message containers. Add class="alertMessage" as attribute to the same.
Instead of $("#alertMessage").show(); use $("#"+formToValidate+" .alertMessage").show();. Define the style for the class .alertMessage as below
.alertMessage {
display: none;
}
I know that it is dumb question to ask but I need to know can I get form widget attributes through PHP I mean not a value but id, class or even parent or child. If I set them.
<label name = '{{ item.modulePath }}' id = 'main' class = 'menu_label' **parent = ''** **childs = ''**>{{ item.modulePath }}</label>
If it is not possible then how can I make JS function before form validation and post array to the form as value?
<form action="{{ path('menu_manage') }}" method="post">
Yes I could get values and submit form to JS and then by JS get all attributes and then through ajax send it to a PHP handler. But it would be longer, because I will need to include all components that have this action to the handle information to place where I need it.
Here is an example how to realize it
http://symfony2forum.org/threads/5-Using-Symfony2-jQuery-and-Ajax
You can call get() method on form field in template, e.g. having a form in form with field item:
{{ form.item.get('id') }}
The class - only if set - can be retrieved like this:
{{ form.item.get('attr').class }}