Django passing parameters to views and templates - django

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>

Related

Django print data of radio button?

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>

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.

How can I access data sent in a post request in Django?

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)

Django: How can I call a view function from template?

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'),

How to translate a form in django

I have a form in a django site
<form method="POST" action="." class="right_custom">{% csrf_token %}
<br>{% trans "Enter the discount coupon code if you have any" %}</br>
<input type="text" name="coupon_code" size="25" maxlength="25" />
<input type="submit" name="submit" value="Caluclate Discount"/>
</form>
I would like to translate the entire site to a lot of languages. I need to translate the button text which is Caluclate Discount. How can I do that? if i use {% trans %} tag, how will the view catch the right post request?
UPDATE
There are many forms on the same page like this and my view uses if postdata['submit']=="Caluclate Discount" to determine which submit request it is.
I was able to get the translation working.
Thanks to the answers by #linux-warrior and #Joachim
Now the form is
<form method="POST" action="." class="right_custom">{% csrf_token %}
<input type="hidden" name="form_name" value="discount_form" />
<br>{% trans "Enter the discount coupon code if you have any" %}</br>
<input type="text" name="coupon_code" size="25" maxlength="25" />
<input type="submit" name="submit" value="{% trans "Caluclate Discount" %}" />
</form>
And i check for if postdata['form_name']=='discount_form' in my view
For buttons, you really don't use the value field for anything else than the button text, so it is straightforward to translate:
<input type="submit" name="submit" value="{% trans "Caluclate Discount" %}"/>
I think that you should use {% trans %} for submit "value". I don't understand why would you need that value inside your view. If you want, you can still give your submit input a custom "name" attribute.
Edit. By the way, your
<br>...</br>
thing inside your form appears to be a bug. You will probably want to make it
<p>...</p>
instead. It is also not recommended to use "submit" name for a type="submit" input (taken from http://api.jquery.com/submit/):
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
Your view doesn't care about what is the submit button's value, so even if you translate it, your view function will work.