I printed my data within the text box as
data = request.GET['information']
print(data)
in views.py
<form class="homepage" action = "{% url 'count' %}" >
<textarea name="information" rows="8" cols="80"></textarea>
<input type="submit" name="" value="Wordecounter">
</form>
It is returning the text from the text box but the question is if I used radio button and selected radio button on my browser then how could I print which option I selected in radiobutton from views.py
You would do exactly the same, so:
data = request.GET['information_radio']
print(data)
And your html:
<form class="homepage" action = "{% url 'count' %}" >
<input type="radio" name="information_radio" value="yes">Yes<br>
<input type="radio" name="information_radio" value="no">No<br>
<input type="submit" name="" value="Wordecounter">
</form>
Related
I got a navigation tree that tells me where i am on my website to build that navigation tree i always need to pass all variables from template to the view as <input type="hidden">. Then i need to pass it from the view to the next template and it goes on and on feels like a bad solution to pass the variables from every template to every view. so my question is if there is a better solution to my problem here is a screen of the navigation tree.
template:
<form action="{% url 'aktentabelle' %}" method="post" style="display:inline-block">
{% csrf_token %}
<input type="hidden" name="mitglied" value="{{Container.containernr}}" />
<input type="hidden" name="contpk" value="{{Container.pk}}" />
<input type="hidden" name="projectnr" value="{{projectnr}}" />
<input type="hidden" name="status" value="{{Container.status}}" />
<input type="hidden" name="chargepk" value="{{chargepk}}" />
<input type="hidden" name="chargenr" value="{{chargenr}}" />
<input class="btn btn-primary" type="submit" value="anzeigen" />
</form>
so in my templates i always need to pass alot of variables as hidden and in my view i need to convert them back to read them:
views.py:
def aktentabelle(request):
assert isinstance(request, HttpRequest)
container = request.POST['mitglied']
z = AkteForm
projectnr = request.POST['projectnr']
chargepk = request.POST['chargepk']
chargenr = request.POST['chargenr']
contpk = request.POST['contpk']
closecontainerform = CloseContainerForm
akte_list = Akte.objects.filter(container__containernr=container)
Anzahl_Akten =Akte.objects.filter(container__containernr=container).count
status = request.POST['status']
return render(
request,
'app/aktentabelle.html',
{
'title':'About',
'akte_list':akte_list,
'anzahl':Anzahl_Akten,
'container':container,
'aktenform':z,
'status':status,
'closecontainerform': closecontainerform,
'date':datetime.now().date,
'contpk':contpk,
'chargepk':chargepk,
'chargenr':chargenr,
'projectnr':projectnr,
}
)
as you can see i use so many lines to just pass all the variables from one template to a view and back to the template again just to build that navigation tree.
One way to do this would be to use filters. Something like below.
from django.template import Library
register = Library()
def get_fields(requested_key):
my_dict={
'title':'About',
'akte_list':akte_list,
'anzahl':Anzahl_Akten,
'container':container,
'aktenform':z,
'status':status,
'closecontainerform': closecontainerform,
'date':datetime.now().date,
'contpk':contpk,
'chargepk':chargepk,
'chargenr':chargenr,
'projectnr':projectnr,
}
return mydict.get("requested_key","")
register.filter('get_fields', get_fields)
Store this in template tags directory with a filename and in your template load this at the top using
{% load filename %}.
Then you can do something like below in your template.
{% load templatefilename %}
<form action="{% url 'aktentabelle' %}" method="post" style="display:inline-block">
{% csrf_token %}
<input type="hidden" name="mitglied" value="{{get_fields|containernr}}"
</form>
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.
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.
I have a form that is supposed to create a new 'Quote' record in Django. A 'Quote' requires a BookID for a foreign key.
This is my form
<form method="POST" action="{% url 'quotes:createQuote' %}">
{% csrf_token %}
<section>
<label for="q_text">Quote Text</label>
<input type="text" name="text" id="q_text" placeholder="Enter a Quote" style="padding-left:3px"> <br>
<label for="q_book">Book ID</label>
<input type="text" name="bookID" id="q_book" placeholder="Enter Book ID" style="padding-left:3px"> <br>
<label for="q_disp">Display Quote Now?</label>
<input type="radio" name="display" id="q_disp" value="True"> True
<input type="radio" name="display" value ="False">False <br>
<button value="submit">Submit</button>
</section>
</form>
And this is the method that it is targeting
def createQuote(request):
#b = get_object_or_404(Book, pk=request.bookID)
return HttpResponseRedirect(reverse('quotes:index'))
Somewhere in that request argument I assume there is some sort of field that contains the bookID the user will pass in on the form. How do I get at that information?
Bonus points for anyone who can tell me some way I can visualise data like I might with console.log(some.collection) in Javascript
if request.method == "POST":
book_id = request.POST['book_id']
Assuming you're sure it's in there. Otherwise you'll need to verify/provide a default value like you would for a normal python dictionary.
As for visualising the data, do you mean printing it to the console? In which case if you're running the django runserver you can just do print some_data. If you want it formatted a little nicer, you can use pretty print:
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(some_data)
I have a question on how to call a view function from a template HTML button? Like an onclick function?
Here is the template:
<input id="submit" type="button" onclick="xxx" method="post" value="Click" />
And the views.py is:
def request_page(request):
...do something...
return render_to_response("/directory.html", {})
Thank you very much.
Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.
inside templateHTML.html:
<form action="#" method="get">
<input type="text" value="8" name="mytextbox" size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
inside view.py:
import mypythoncode
def request_page(request):
if(request.GET.get('mybtn')):
mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')
One option is, you can wrap the submit button with a form
Something like this:
<form action="{% url path.to.request_page %}" method="POST">
<input id="submit" type="button" value="Click" />
</form>
(remove the onclick and method)
If you want to load a specific part of the page, without page reload - you can do
<input id="submit" type="button" value="Click" data_url/>
and on a submit listener
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
success: function(data){ $('#target').html(data) }
});
});
});
How about this:
<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>
The class is including bootstrap styles for primary button.
you can put the input inside a form like this:-
<script>
$(document).ready(function(){
$(document).on('click','#send', function(){
$('#hid').val(data)
document.forms["myForm"].submit();
})
})
</script>
<form id="myForm" action="/request_page url/" method="post">
<input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>
For deleting all data:
HTML FILE
class="btn btn-primary" href="{% url 'delete_product'%}">Delete
Put the above code in an anchor tag. (the a tag!)
url.py
path('delete_product', views.delete_product, name='delete_product')]
views.py
def delete_product(request):
if request.method == "GET":
dest = Racket.objects.all()
dest.delete()
return render(request, "admin_page.html")
For example, a logout button can be written like this:
<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>
Where logout endpoint:
#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),