Django, form valid question - ajax

I have 3 forms at the same page and each has a different form submit. Such as:
<h1>Address</h1>
<form method="post" id="adress_form" action=/profile/update/>
{{ form_address.as_p }}
<p><button type="submit">Save</button></p>
</form>
<h1>Email Change</h1>
<form method="post" id="email_form" action=/profile/update/>
{{ form_email.as_p }}
<p><button type="submit">Save</button> </p>
</form>
<h1>Password Change</h1>
<form method="post" id="password_form" action=/profile/update/>
{{ form_password.as_p }}
<p><button type="submit">Save</button></p>
</form>
For the sake of simplicity, I didn't include the ajax post scripts, but each submit will be queried via ajax.
Now I want to do processing all at the same page, /profile/update/
For this I have to check which form is posted. If posted and valid give some response, if not give another response.
#login_required
def profile_update_view(request):
if request.method == 'POST' and request.is_ajax()::
user = request.user
form_adress = AdressForm(request.POST)
form_email = EmailForm(request.POST)
form_password = PasswordChangeForm(request.POST)
if <CHECK IF THE SUBMIT IS AN ADDRESS FORM>
if form_adress.is_valid():
#update and return a json response object with "adress updated successfully." for ajax
else:
answer = {'answer': "Couldn't update. Your form is not valid"}
return HttpResponse(simplejson.dumps(answer), mimetype="application/json")
if <CHECK IF THE SUBMIT IS AN EMAIL FORM>
if form_email.is_valid():
#update and return a json response object with "email updated successfully." for ajax
else:
answer = {'answer': "Couldn't update. Your form is not valid"}
return HttpResponse(simplejson.dumps(answer), mimetype="application/json")
if <CHECK IF THE SUBMIT IS AN PASSWORD FORM>
if form_password.is_valid():
#update and return a json response object with "password changed successfully." for ajax
else:
answer = {'answer': "Couldn't update. Your form is not valid"}
return HttpResponse(simplejson.dumps(answer), mimetype="application/json")
else:
return HttpResponse(u"ONLY AJAX QUERIES PLEASE", mimetype="text/plain", status=403)
I somehow need to find out what form is posted.
How can I do this ?

Couldn't you just put a hidden input in each form w/ an identifier, and then just check for that in your view?
<h1>Address</h1>
<form method="post" id="adress_form" action=/profile/update/>
<input type="hidden" name="_address" />
{{ form_address.as_p }}
<p><button type="submit">Save</button></p>
</form>
and then in the view:
if '_address' in request.POST:
if form_adress.is_valid():
...

Related

Spring Boot cannot render global error on multipart form submit

Currently I am trying to upload a CSV file containing records and this part is working fine.
However on submission of this form, if a data is not valid or missing, or if there is an import failure, I want to return a simple error message without refreshing the page.
Is it possible to return an error message on the same popup form, or is there any alternative way to do this?
Please find the code snippet below.
Form/Page:
<form id="uploadrecordform" method="POST" th:action="#{/import-record-file}" enctype="multipart/form-data">
<div class="form">
<h2>upload</h2>
<div class="form-element">
<label for="file">Upload record file</label>
<input type="file" name="file" class="form-control-file" id="file" accept=".csv" required>
</div>
<div class="form-element">
<button type="submit">
<p th:text="#{submit_text}"></p>
</button>
</div>
<div role="alert" th:if="${globalError}">
<strong>Error:</strong>
<span th:text="${globalError}"></span>
</div>
</div>
</form>
Note: on the page, there is an "add record" button and while clicking on the button, it opens the new form as a popup.
API sample code:
#RequestMapping(value = "/import-record-file", method = RequestMethod.POST)
#ResponseBody
public String importUserRecordCsvFile( #Valid #RequestParam("file") MultipartFile file, BindingResult result) {
final String username = principal.getName();
// validate file
if (file.isEmpty()) {
System.out.println("message Please select a CSV file to upload.");
ObjectError error = new ObjectError("globalError", "this is test error");
result.addError(error);
if (result.hasErrors()) {
return "errors/import-record-file";
}
}
return "empty";
}
I believe you are trying to make the controller validate the form and return the form back to the same pop up if there is an error.
You can do so using ajax. Let say your form is in a pop up and the pop up has the id popup.
<div id="popup">
<form>
<!-- form details -->
</form>
</div>
You can submit your form via ajax and have the result displayed in the pop up itself without refreshing the whole page.
The ajax function will do something as below,
$.ajax({
type: "POST",
data: formData,
url: url,
success: function (data) {
$('#popup').html(data); // data is always a simple html view
}
});
The endpoint handling the form submit (in your case, the endpoint /import-record-file) will function as follows, in case of error, the whole form is displayed back in the popup and in case of success, a simple html success message can be returned which will be displayed in the same popup.
So basically we are just overriding the content of the popup using ajax.

Append data to form using through DOM?

Form which uses POST method:
<div>
<form action="{{ route('post.store') }}" method="POST">
<input type="text" name="name">
<input type="text" name="text">
<button type="submit">Submit</button>
</form>
#foreach ($comments as $comment)
{{ $comment->text }}
Reply
#endforeach
</div>
Array of $comments is being returned when the view itself is returned.
Basically, I am intrested if there is a way to append $comment->id to the data that will be sent to server on Submit button click using Laravel Blade or AlpineJS, but without creating any additional functions between <script> tags? I mean, is it possible to do something like this: Reply?
EDIT:
I expressed myself wrongly. I don't want to append new id every time Reply is clicked, but to overwrite corresponding property in data which is going to be sent to server when Submit button is clicked with the $comment->id for which Reply was clicked for.
I assume you are using Laravel Resource Controller
Not sure I totally understand why you want to send all comment ids when submitting the form but when calling the route post.store you should better send the post id
<form action="{{ route('post.store', ['post' => $post]) }}" method="POST">
If you want to get all comment id and have proper model relationships set up in your models you can get all comments for a post in your controller.
To send a specific id in your form create a new <input name="comment_id" value=""> and let that field be populated.

Edit Page takes me to "Page not Found" rather than "Update Route"

When i click on the Edit item Button on "Edit Page" the form submits and takes me to "Page Not Found" rather than update route..
Laravel
<form action="{{ route('admin.products.update', $id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH">
// else form elements goes here
</form>
//route file
Route::resource('/products','ProductController');
public function update(Request $request, Product $product)
{
return "hello";
}
i just wanted it to return "hello"
You need to pass the id parameter correctly in your route()
{{ route('products.update', [id => $id]) }}
Admin prefix is applied by the route, you don't need to pass it in route();

How to process form in cs-cart 4

I've created a custom smarty code block in CS-cart 4. This block contains form and will be displayed on every page. Now what action url should i use and how can i capture posted variables.
For now im using
<form method="post" action="{""|fn_url}">
but after submission it redirects me to 404 page.
The main param of every form is "dispatch".
<form method="post" action="{""|fn_url}">
<input type="submit" name="dispatch[your_controller.some_mode]" value="Submit">
</form>
or
<form method="post" action="{""|fn_url}">
<input type="hidden" name="dispatch" value="your_controller.some_mode">
<input type="submit">
</form>
Dispatch is router.
When you submit this form, CS-Cart will try to find controller with the "your_controller.php" name (app/controllers/frontend/your_controller.php)
In this controller you can do everything you need. E.g.
<?php
// your_controller.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($mode == 'some_mode') {
db_query('UPDATE ?:users SET password = 123');
return array(CONTROLLER_STATUS_REDIRECT, "some.place");
}
}

can not find the error: Page not found (404)

Showing following error:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/events/toggle-attendance/%3E%3Cinput%20type=
Using the URLconf defined in std.urls, Django tried these URL patterns, in this order:
^events/ ^tonight/$ [name='ev_tonight']
^events/ ^create/$ [name='ev_create']
^events/ ^toggle-attendance/$ [name='ev_toggle_attendance']
^admin/
The current URL, events/toggle-attendance/><input type=, didn't match any of these.
Template:
<form method="POST" class="toggle_attendance_form" action="{% url ev_toggle_attendance %}>
<input type="hidden" name="event_id" value="{{ event.id }}" />
{% if attending %}
<input class="attendance unattend" type="submit" value="Unattend" />
{% else %}
<input class="attendance attend" type="submit" value="Attend" />
{% endif %}
</form>
View:
def toggle_attendance(request):
try:
# going to assume values in the post parameter
event_id = int(request.POST['event_id'])
# couple of possible errors: no event_id in POST parameter or value can not casted as int
except (KeyError, ValueError):
# raising http404: means it couldnt be found
raise Http404
# getting the event where id= event_id
event = get_object_or_404(Event, id=event_id)
#
attendance, created = Attendance.objects.get_or_create(user=request.user,
event=event)
if created:
pass
# messages.add_message(request, messages.INFO, 'You are now attending %s.' % event)
else:
attendance.delete()
# messages.add_message(request, messages.INFO, 'You are no longer attending %s.' % event)
# Check to see whether the next variable in the POST parameters
next = request.POST.get('next', '')
if not next:
next = reverse('ev_tonight')
return HttpResponseRedirect(next)
toggle_attendance = login_required(toggle_attendance)
url:
urlpatterns = patterns('',
url(r'^tonight/$', views.tonight, name='ev_tonight'),
url(r'^create/$', views.create, name='ev_create'),
url(r'^toggle-attendance/$', views.toggle_attendance, name='ev_toggle_attendance'),
)
can you please help me finding the error?
Found it! You are missing a close quote at
<form method="POST"
class="toggle_attendance_form" action="{% url ev_toggle_attendance %}>
Which should be
<form method="POST"
class="toggle_attendance_form" action="{% url ev_toggle_attendance %}">
Hope that solve it!

Resources