Submitting button inside a form selenium + python - django

I have this form which contains a button with some dynamic value, when I click on it it should add the product to the checkout page.
Here is the html form :
{%for p in product %}
<div class="single-product">
<div class="product-f-image">
<img src="data:image/png;base64,{{p.image_medium}}" alt="">
<div class="">
{% if not user.is_authenticated %}
<form action="/login/">
<button class="add-to-cart-link" type="submit"> Add to cart</button>
</form>
{%else%}
<form id="form-id" action="" method="POST">
{% csrf_token %}
<button class="add-to-cart-link" type="submit" name="product" value="{{p.id}}" >
<input type="hidden" name="product_name" value="{{p.name}}">
<input type="hidden" name="product_price" value="{{p.lst_price}}">
Add to cart</button>
</form>
{%endif%}
<i class="fa fa-link"></i> See details
</div>
</div>
<h2>{{p.id}}</h2>
<div class="product-carousel-price">
<ins>{{p.lst_price}} €</ins>
</div>
</div>
{%endfor%}
And here is my what I am doing with selenium:
bon_commande = self.selenium.find_element_by_xpath("//button[#name='product' and #value='37']/parent::form")
bon_commande.submit()
And thanks for the help !

You don't need to locate Submit button to submit a form - use any element inside form or form element itself:
self.selenium.find_element_by_id("form-id").submit()
self.selenium.find_element_by_class_name("add-to-cart-link").submit()
Update
Try to wait until django variable "{{p.id}}" is replaced with generated value:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.XPATH, "//button[#name='product' and #value='37']"))).submit()

Change to click the submit button:
// add some sleep to wait the JS files of page
// load completely to register click event to the submit button
// otherwise nothing to response to the click
// (because the `action` of the form is empty.)
self.selenium.sleep(15); // sleep 15 seconds
self.selenium.find_element_by_xpath("//button[#name='product' and #value='37']").click()

To click on the button with text as Add to cart you can use the following line of code :
self.selenium.find_element_by_xpath("//form[#id='form-id']/button[#class='add-to-cart-link' and #name='product']").submit()
#or
self.selenium.find_element_by_xpath("//form[#id='form-id']/button[#class='add-to-cart-link' and #name='product']").click()

Related

How do I make my livewire store method send data using POST, seems it is using a GET method

public function storeProject()
{
$this->validate();
$fileName = $this->files->store('uploads');
Project::create([
'title' => $this->title,
'description' => $this->description,
'files' => $fileName,
'skills' => $this->skills,
]);
session()->flash('message', 'Your Project has been posted Successfully!');
}
My View
#section('title', 'Post a job')
<div>
<div class="py-12 font-sans">
<div class="max-w-5xl mx-auto sm:px-6 lg:px-8">
<div class="m-4 p-4 bg-gradient-to-r from-blue-800 via-blue-700 to-blue-600 text-white rounded-md">
<h2 class="text-4xl">Tell us what you need done!</h2>
<p class="break-words mt-5">Within minutes, get in touch with knowledgeable independent contractors. View
their profiles, give them feedback, look at their portfolios, and talk with them. Only pay the
freelancer once you are completely satisfied with their job.
</p>
</div>
<div>
{{-- Form is located here --}}
<form enctype="multipart/form-data">
<div class="mb-6">
<label for="title">Choose a Title for your Project</label>
<input type="title" id="title" name="title" wire:model.lazy="title"
placeholder="e.g. Build me a website">
</div>
<div class="mb-6">
<label for="message">Tells more about your project</label>
<textarea id="description" name="description" rows="4" wire:model.lazy="description"
placeholder="Describe your project here..." maxlength="4000"></textarea>
</div>
<div class="mb-6">
<label for="user_avatar">Upload file</label>
<input wire:model="files" aria-describedby="user_avatar_help" id="user_avatar" name="files"
type="file">
</div>
<div class="mb-6">
<label for="skills">
What skills are required</label>
<p class="break-words mt-2">Enter up to 5 skills that best describe your project. Freelancers
will use these skills to find projects they are most interested and experienced in.</p>
<input type="text" id="skills" name="skills" data-role="tags-input"
wire:model.lazy="skills" placeholder="Enter skills here separated by commas...">
</div>
<button type="submit" wire:click="storeProject">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. This is my blade code.
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
You need to change the form tag and the submit button:
<form wire:submit.prevent="storeProject">
<button type="submit">
Submit
</button>
This will take care of the page refresh and the GET call. You do not need enctype="multipart/form-data" when using Livewire.
I think that you have created a controller function storeProject() and a blade view with your <form enctype="multipart/form-data"> which is completely wrong. Check here how livewire should work https://laracasts.com/

django python form to submit, delete row from database and refresh page

I am newbie in Django and I would appreciate if someone can help me about this problem.
I have a database in backend with 100 rows of users information.
Name, surname, phone number.
The database is visible on Home page template and if you choose one of this names you can donate something to this person.
When you click on submit button will lead you to new ajax window where you input your data and then submit.
Then I got your message on email.
My questions is how to do at the same time to confirm (submit) and delete row from database (person from database) and then to refresh page ?
Meaning, when you submit form then function should delete person from Home page at once and have to refresh page so you can see another person ?
Here is the code.
I would appreciate any help.
Thanks to all.
views.py
def about(request):
context = {
'num_toys': '1',
}
return render(request, 'about.html') # , context=context
def couses(request):
db_queryset = Children.objects.all()
context = {'child': db_queryset}
return render(request, 'couses.html', context=context)
class ChildrenListView(ListView):
model = Children
context_object_name = 'child'
class ChildrenCreateView(CreateView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_changelist')
class ChildrenUpdateView(UpdateView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_changelist')
class ChildrenDetailView(DetailView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_detail')
children_detail.html
<!-- Start contact form area -->
<div class="couses">
<section class="contact-form-area pb-60 pt-90">
<div class="couses">
<div class="container">
<div class="row">
<!-- Start section title -->
<div class="col-sm-12">
<div class="section-title text-center">
<h2>Donate <span> {{ children.toy }} </span> to <span>{{ children.name }}</span> who is <span>{{children.date }} old</span></h2>
<img src="static/children/img/title-bottom.png" alt="">
</div>
</div>
<!-- End section title -->
<div class="col-sm-12">
<div class="contact-form">
<form id="contact-form" method="POST" action="mail.php">
<div class="form-fields">
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Your Name" required>
</div>
<div class="form-fields">
<label for="email">Email</label>
<input id="email" name="email" type="text" placeholder="Your Email" required>
</div>
<div class="form-fields last">
<label for="phone">Phone</label>
<input id="phone" name="phone" type="text" placeholder="Your Phone" required>
</div>
<div class="message-fields">
<label for="mess">Message</label>
<textarea name="mess" id="mess" cols="30" rows="10" placeholder="Message"></textarea>
</div>
<div class="form-button">
<button type="submit">Send your message</button>
<button type="reset">Reset</button>
</div>
</form>
<p class="form-messege"></p>
</div>
</div>
</div>
</div>
</div>
</section>
sorry if I'm wrong but I understand that you want to do two actions.
In your code I can see that you have forms and class-based Views. Maybe you need to override the function form_valid to do the operations you need when you submit.
Check this website http://ccbv.co.uk there you will find the details of the views.
On click of submit hit the url & process your message on email part first and then you can delete the person from database by filtering out object of that particular person with whatever primary key you have for that table by writing a query in your view. and then render the remaining data of that table to your template on which you are Redirecting from your on submit click.
From above conversation what i understood that you don't want delete that person from database boolean field would be great option rather you want to save the message that has been sent from email by this way you can do both at the same time. you have the message saved in your database and from empty message data can render those user on template.

django CMS don't show toolbar on login

I'm looking for a way to not automatically show the CMS toolbar (version 3.3.0) when a 'staff-user' logs in.
The toolbar should only be activated when ?edit is in the URL.
The documentation mentions the CMS_TOOLBAR_HIDE option, but I don't see any effects when enabled. Also the description:
"If True, the toolbar is hidden in the pages out django CMS."
seems not totally clear to me...
Any ideas?
If you add ?toolbar_off to the URL the toolbar disappears completely (no toggle button). ?edit turns it back on.
To automatically turn it off:
(A) You'd could add something like a middleware or hook into the login chain and add the parameter there.
(B) You might subclass/extend the CMSToolbar to override the following default behavior:
def init_toolbar(self, request):
self.request = request
self.is_staff = self.request.user.is_staff
self.edit_mode = self.is_staff and self.request.session.get('cms_edit', False)
self.show_toolbar = self.is_staff or self.request.session.get('cms_edit', False)
if self.request.session.get('cms_toolbar_disabled', False):
self.show_toolbar = False
Especially the last lines would have to be changed to use a default of True:
if self.request.session.get('cms_toolbar_disabled', True):
self.show_toolbar = False
I have overridden the login.html and adding a trailing ?toolbar_off to the {{ next }} hidden input value.
<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
<div class="form-element-wrapper">
<input class="form-input" type="text" name="username" autofocus="" maxlength="254"
required="" id="id_username" data-cip-id="id_username">
<span class="form-input-highlight"></span>
<span class="form-input-bar"></span>
<label for="username" class="form-label">Username</label>
</div>
<div class="form-element-wrapper">
<input class="form-input [% password_css %]" type="password" name="password" required=""
id="id_password" data-cip-id="id_password">
<span class="form-input-highlight"></span>
<span class="form-input-bar"></span>
<label for="password" class="form-label">Passwort</label>
<!-- THIS IS THE IMPORTANT LINE! -->
<input type="hidden" name="next" value="{{ next }}?toolbar_off"/>
</div>
<div class="form-element-wrapper">
<button class="form-element form-button" type="submit"
value="{% trans 'Log in' %}">{% trans 'Log in' %}</button>
</div>
</form>
Just a little solution if a user signs in via the login page. This does not affect the login via ?edit.

double-submit issue in browsers - Bootstrap + Django

I have Bootstrap modal window for updating data everytime I close it, I face the so-called double-submission problem. That is, if I press F5, a message pops up telling me that I'm going to submit the same data for the second time and it inserts records into my table if I press ok. Moreover, if I try to open the modal window for the second time, it is rendered incorrectly ! Does it have anything to do with Django somehow ?
The modal window:
<form class="modal fade" id="openTaskWindow" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" method="post">{% csrf_token %}
<div class="modal-dialog modal-lg form-horizontal" role="form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Новая задача</h4>
</div>
<div class="modal-body" style="font-size: smaller">
{{ createTask_form.as_p}}
</div>
<div class="modal-footer">
<input class="btn btn-default btn-sm" type="submit" value="Сохранить"/>
</div>
</div>
</div>
</form>
The button that calls the window:
<div><button type="button" data-toggle="modal" data-target="#openTaskWindow" data-backdrop="static" data-keyboard="false">Launch my modal</button></div>
The view (that is called when submit button of the modal window is pressed):
def createTask(request):
taskTable = Tasks.objects.all()
if request.method == 'POST':
task_form = TaskForm(request.POST)
if task_form.is_valid():
temp_form = task_form.save(commit=False)
temp_form.is_important = 0
temp_form.save()
return render_to_response('task_management/task_list.html',{'createTask_form':temp_form, 'taskTable': taskTable},context_instance=RequestContext(request))
else:
task_form = TaskForm()
return render_to_response('task_management/task_list.html',{'createTask_form':task_form, 'taskTable': taskTable, 'task_id':''},context_instance=RequestContext(request))
After reading discussions of the community, I tried to do this:
$('#openTaskWindow').submit(function() {
location.href = location.href;
});
but it did not help. Any ideas?
Well, this has not much to do with Django. The browser cache the post request for re-submission. The easiest way to prevent this is to return HttpResponseRedirect when for is valid.
So instead
if task_form.is_valid():
temp_form = task_form.save(commit=False)
temp_form.is_important = 0
temp_form.save()
return render_to_response('task_management/task_list.html',{'createTask_form':temp_form, 'taskTable': taskTable},context_instance=RequestContext(request))
Try to do
if task_form.is_valid():
temp_form = task_form.save(commit=False)
temp_form.is_important = 0
temp_form.save()
return HttpResponseRedirect('your_url')
And if you need to pass some extra arguments to the view you can accomplish that through query string or session based cache. And you don't need your Javascript hack.

Django template filter escaping

I've got a custom filter that takes a string and makes it into the appropriate attributes for the tooltip library I'm using. It worked with OpenTip, but I'm converting to using the tooltip library that's in Bootstrap.
Here's my filter:
from django import template
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
register = template.Library()
#register.filter(needs_autoescape=False, is_safe=True)
def tooltip(value, autoescape=False):
"""
Filter to turn some text into the tag that the tooltip library uses -
Written as a filter so we can switch from one tooltip library to
another
"""
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
if value is not None and len(value) > 0:
retval = 'data-toggle="tooltip" data-html="true" ' +\
'rel="tooltip" title="%s"' % esc(value)
return mark_safe(retval)
else:
return ''
And here's where I'm using it in a template:
<form id="filter" name="filter" method="post"
class="form-inline">
{% csrf_token %}
<label for="filterText">Filter Query:</label>
<input type="text" id="current_filter" name="current_filter" value="{{current_filter}}" placeholder="Filter" class="span8"/>
<i class="icon-question-sign"
{{"Filters -<br>requester: [[first] [last]]|[windows_id]<br>client: [[first] [last]]|[windows_id]<br>approver: [[first] [last]]|[windows_id]<br>worker: [[first] [last]]|[windows_id]<br>ticket: [id]<br>status: [open]|[closed]|[hold]<br>type: [termination]|[extension]|[access]|[password]|baskets]<br>item: [name for category/item/attribute inventory]<br>since: [mm/dd/yyyy]|[yyyy-mm-dd]<br>before: [mm/dd/yyyy]|[yyyy-mm-dd]<br>All searchs are AND with comma delimiting"|tooltip}}></i>
<input type="submit" name="btnSubmit" class="btn" value="Filter"/>
<input id="filter_reset" type="button" name="filter_reset" class="btn" value="Clear existing filters"/>
</form>
{% endif %}
But the tooltip isn't processing the html, and when I go into Firebug and cut and paste the html, it looks like something is escaping it in spite of the fact that I marked it with mark_safe:
<form class="form-inline" method="post" name="filter" id="filter">
<input type="hidden" value="dpuAc9GNUQtvGG5wYzrWsG2Vpu5i7PWJ" name="csrfmiddlewaretoken">
<label for="filterText">Filter Query:</label>
<input type="text" class="span8" placeholder="Filter" value="" name="current_filter" id="current_filter">
<i title="Filters -<br>requester: [[first] [last]]|[windows_id]<br>client: [[first] [last]]|[windows_id]<br>approver: [[first] [last]]|[windows_id]<br>worker: [[first] [last]]|[windows_id]<br>ticket: [id]<br>status: [open]|[closed]|[hold]<br>type: [termination]|[extension]|[access]|[password]|baskets]<br>item: [name for category/item/attribute inventory]<br>since: [mm/dd/yyyy]|[yyyy-mm-dd]<br>before: [mm/dd/yyyy]|[yyyy-mm-dd]<br>All searchs are AND with comma delimiting" rel="tooltip" data-html="true" data-toggle="tooltip" class="icon-question-sign">
</i>
<input type="submit" value="Filter" class="btn" name="btnSubmit">
<input type="button" value="Clear existing filters" class="btn" name="filter_reset" id="filter_reset">
</form>
How do I get the html in that filter text into the page without the being escaped?
Try using safe:
{{"Filters -<br>requester: [[first] [last]]|[windows_id]<br>client: [[first] [last]]|[windows_id]<br>approver: [[first] [last]]|[windows_id]<br>worker: [[first] [last]]|[windows_id]<br>ticket: [id]<br>status: [open]|[closed]|[hold]<br>type: [termination]|[extension]|[access]|[password]|baskets]<br>item: [name for category/item/attribute inventory]<br>since: [mm/dd/yyyy]|[yyyy-mm-dd]<br>before: [mm/dd/yyyy]|[yyyy-mm-dd]<br>All searchs are AND with comma delimiting"|safe|tooltip}}
Or you can try removing esc from your tooltip tag.
Edit:
I just realized what you are trying to do. You cannot put html inside a tooltip in bootstrap, it's a plaintext feature only. data-html="true" allows it to contain html content. You can also use popover. Above safe filter should still be used in order to disable html escaping.
Turns out the problem was much stupider than what I thought it was - I had my <script> tags in the wrong order so I was getting the jQuery-UI tooltip instead of the Bootstrap tooltip, and the jQuery-UI tooltip doesn't support html.