I'm probably missing something very basic but I'm stumped.
My HTML form (in a Django template):
<form id="site_signout" method="POST">{% csrf_token %}
<input type="submit" value="sign in">
</form>
In my browser (running my site on the dev server), when I click on the <input> button, nothing happens. Like, nothing nothing. Normally something would show in Terminal such as
[22/Apr/2014 08:29:17] "POST /my/url/ HTTP/1.1" 302 0
Or in Firebug, I would see something about a POST in the HTML tab of the Net panel. But I see nothing. Literally nothing happens when I click the button.
Other submit buttons (for other forms) on my site work just fine.
What could be causing this?
EDIT: The relevant part of my view is:
if request.method == 'POST':
pdb.set_trace()
That's all I have for the form right now because I want to examine what is posted in this scenario before I write more code.
EDIT: My intention is to simply POST to the same page (URL) that the form is on. As I understand it, this should be achievable by simply omitting the action attribute of the <form> element altogether. This is how I started but since it didn't work, I tried a couple of other options such as action="/", which is what I originally posted above. However, my intention is to have the form POST handled by the same view as the form itself. Therefore I've edited my original code sample to omit the action attribute altogether to clarify this point.
Here is my top-level urls.py:
urlpatterns = patterns('',
url(r'^inspection/', include('main_inspection.urls') ),
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is main_inspection.urls with the relevant URL:
urlpatterns = patterns('main_inspection.views',
url(r'^home/$', 'home', name="inspection_home"),
...
)
The URL for the view in question (on my dev server) is:
http://127.0.0.1:8000/inspection/home/
The solution turned out to be quite silly, and not discoverable by anyone reading the above question:
I had some JS capturing any click event happening inside the div in which the form was located.
Lesson learned: when something really strange seems to be happening at the basic HTML level, check to make sure you didn't write any stupid JS code that is producing the effect.
Your URL about "/" should be something like this:
...
url(r'^$','yourapp.views.index',name="base_address"),
...
It will run "yourapp.views.index" when you call "/" address.
If you want to set an address in you form action attribute try to set name of address instead:
<form id="site_signout" method="POST" action="{% url 'base_address' %}">{% csrf_token %}
<input type="submit" value="sign in">
</form>
We defined "base_address" name in urls that assigned to "/" address and then used that with "url" method in template.
Related
I am very new to Django and trying to make my first project. I find it difficult to use the buttons I created to move to the selected URL.
Let's say my app is called TestForms and my models are: Patients, General, PST and ERBT. I would like to create two buttons - 'Previous' and 'Next' - which will be used to go to previous/next forms respectively. I try to do so using admin templates in django.
NOTE: I know changing built-in templates are not a very good idea, I will create new html file to extend this templates before doing changes on the server. For now I am doing it locally on my computer.
In submit_line.html I created two new buttons and they are like so:
{% if show_save_and_go_to_next_form %}<input type="submit" value="{% translate 'Next' %}" class="default" name="_gotonextform">{% endif %}
{% if show_save_and_go_to_previous_form %}<input type="submit" value="{% translate 'Previous' %}" class="default" name="_gotopreviousform">{% endif %}
This gives me two good-looking buttons on the site.
But these are just saving the results (working like 'Save' button), but not redirecting me to the next form as I would like to. When I am adding a new patient (admin/TestForms/patient/add/), after clicking on 'Next' I would like the server to save this patient and redirect me to admin/TestForms/general/add/ to be able to fullfil the next form, then save the changes and move on to admin/TestForms/PST/add/and so on.
I know I have to add the anchor, but I tried multiple times with different approaches and nothing worked. When I try to use <a href ...>, the button disappears. Also it is difficult for me to figure out how to move from one form to another and to disable the 'Previous' button on the first form and the 'Next' button on the last form.
Any suggestions how to achieve it?
The redirect needs to be done in your view, not in the template.
def your_view(request, *args, **kwargs):
# your code ...
if request.POST.get('_gotonextform'):
return redirect('admin/TestForms/general/add/')
else:
# do whatever you like if any other button was clicked
pass
I have a contact form that appears at the bottom of every page in the footer. I simply included it in my base.html at the bottom. Now i want to figure out a way to submit it. All the examples wagtail provides is under the assumption i have an entire page dedicated to it and hence submits to itself.
This cannot work for me as its not a page.
I have written pseudo code of what I think it should look like .
def submitContact(request):
source_email = request.POST.get('email')
name = request.POST.get('name')
message = request.POST.get('message')
if (source_email is not None) and (name is not None) and (message is not None):
body = "sample"
send_mail(
name,
message,
source_email,
['test#foobar'],
fail_silently=False,
)
Then my form would be something like this
<form class="form-group" role="form" method="post" action="/submitContact">
......
</form>
Ideally if someone could point to Wagtail resources that show how to create endpoints in models that do not inherit from the Page model and are not snippets that maintain "request" content that would be useful. Ideally what I would prefer is to log this data into contact "table" then send the email after.
What should I add to my urls.py to reroute the request with the correct context for the function to retrieve the required variables and thus send the email
Additional info
I wrapped a snippet around the footer to provide some context to it using templatetags, just putting this out there incase it adds value
See below.
#register.inclusion_tag('home/menus/footer.html', takes_context=True)
def footers(context):
return {
'footers': Footers.objects.first(),
'request': context['request'],
}
You should use {% url %} template tag.
urls.py :
from django.conf.urls import url
from yourapp.views import submitContact
urlpatterns = [
url(r'^contact/$', submitContact, name='contact'),
]
Template :
<form class="form-group" role="form" method="post" action="{% url 'contact' %}">
......
</form>
Another improvement is to use Django Form.
Note : prefer lower_case_with_underscores naming style for functions. Use CamelCase for classes. See PEP8 for more information.
Instead of trying to build it yourself, why not take a look at the already existing Form Builder of Wagtail?
It enables you to create a FormPage on which you can display a custom form and even E-mail the results.
Check out the documentation here.
I have been learning Sinatra for a couple of days now so I am still quite new. I am simply created a notes application and have added a delete function within the app.
Here is my Controller:
# Will display title of all notes
get '/' do
#notes = Note.all
erb :index
end
# Will display content within selected note
get '/:id' do
#note = Note.where(id: params[:id]).first
erb :note_description
end
# Will delete item from notes.
delete '/:id' do
Note.delete(params[:id])
redirect '/'
end
Here is my view with html/erb:
<div class="container">
<p>Return to Notes</p>
<h1><%= #note.title %></h1>
<p><%= #note.content %></p>
<form onsubmit="confirm('Are you sure you want to delete the following note?')" action="/<%= #note.id %>" method="POST">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete</button>
</form>
</div>
As you can see, I have created a delete button and have a pop-up on submit when you click it. This will simply verify if the user really wants to delete the object. What happens though, is no matter what I click the item will be deleted and I will be redirected to the home page. I want to add logic where the app will only delete and redirect me to home page if the user clicks okay. If they click cancel nothing should happen. Any advice or help would be greatly appreciated.
You need to return from the event handler itself, so the attribute will look like:
onsubmit="return confirm('Are you sure you want to delete the following note?')"
Currently the return value of return is being returned to the event handler, but the handler itself is returning true (or at least not false).
(The current recommendation seems to be to avoid inline event handling like this though.)
You are seeing this behavior because the client is doing a POST, not a DELETE.
HTML forms only know how to do GET and POST. They cannot do PUT or DELETE. One way you can make it work is by using an AJAX call.
If you are using JQuery, you can set the method to DELETE. Here is the reference.
You will need to create the URL: /1 for example. And you need to handle the success and failure cases. Perhaps set the location on success, and display an error on failure.
EDIT: According to Matt's comment below, _method param replaces the HTTP method. Even though this works, I don't think it is a good practice. It would be better to use the HTTP DELETE method.
When I was learning Php with Mysql, I got a problem :
<form action="?" method="POST">
.
.
.
</form>
Why do we put "?" in the action attribute?
PS: this form was for inserting text into a database.
Actually, I have an Index.php file which is the controller, and 2 files (form.html.php and joke.html.php as templates). In the tutorial, I first clicked on a link "add joke" to include the form.html.php file and in this form there is <form action="?"> </form> and a submit <input>. When I click on submit, the controller index tests and executes the inserted SQL query.
Thanks.
Personally don't ever do that.... Use action="action.php" or use action="" post to the current URL.
Not sure what you are trying to accomplish with ? in the action attribute.
"We" don't and "You" shouldn't do so either.
If you want to POST the data to the current URL, leave it empty, i.e. action="".
If you want to POST to another URL, put that URL in there, e.g. action="save.php".
I'm running Firefox 2.0.0.14.
I have a form on a webpage which is working fine with the GET method.
I'm using a plugin to view my browser's HTTP request when submitting the form, and here it is :
GET /postComment.php?review=2&comment=Testing HTTP/1.1
...
However, if I make the simple change from method=GET to method=POST on the form:
GET /postComment.php HTTP/1.1
...
It isn't even attempting to POST.
Any possible reasons for this, under any circumstances?
EDIT: Here is the form:
<form method=POST action="postComment.php"><input type=hidden name=review value="2"><input type=submit value="Postit">
</form>
Is the action parameter of the form tag set? Could Javascript be intercepting the post? Some HTML from your form would be helpful, or an example link :)
I'm guessing your plugin is not capturing the POST variables. Since the output of your plugin is:
GET /postComment.php HTTP/1.1
How are you catpuring your POST varables? $_POST['key'] or $_REQUEST['key'] should contain your value if the form action and method are set properly.
POST will not be found in the query string.
EDIT:
if you are trying to capture the post value, you can check it with something like this:
if (isset($_REQUEST['submit'])) {
echo $_REQUEST['review'];
}
or
if (isset($_POST['submit'])) {
echo $_POST['review'];
}
Acorn
I would start by making sure your HTML is valid XHTML. Wrap attribute values in quotations and end the input elements with />. Use a valid DOCTYPE.
Also, try changing the value of the submit button to "submit" (as that is the default).
Try it out in different browsers, including the latest version of Firefox.
Firstly, your <form> tag needs to be adjusted:
<form method="post" ... >
Secondly, I have a function called debugArray that I use to spit out misbehaving arrays. It's very handy:
function debugArray($array){
echo("<pre>");
print_r($array);
echo("</pre>");
}
Then, call it in your code like this:
debugArray($_POST);
By looking at the entire contents of the $_POST array, you can see exactly what is being sent, what is not, and how it is being sent.
I'm willing to wager that one of the following is true:
You have a spelling mistake in a field name, remembering that names are case sensetive.
Your form field is outside your <form> tags.
You have a value that is not being escaped correctly, or otherwise being dropped from the $_POST for whatever reason.
Edit: And I would also be inclined to update your copy of Firefox.
I was having the same problem, till I remembered that my .htaccess file hides my PHP extension, and for reasons that someone else can explain (tech stuff) All I did was remove the .php extensión in the action property and it worked.
So, I went from:
action="folder/folder/file.php"
To:
action="folder/folder/file"
And the print_r($_POST) displayed the full array
I really Hope this helps someone else with the same problem.
And if anyone can technically explain why this is happening, it would be very educational 🙃