How to get an input from a base template in Django? - django

I would like to have a little text area in which people can write something and immediately post it to the database. So, I need a way to manage an input from a base template. I know how to do this with normal templates, but I can't figure out how to do it with the base template without writing the same process in every child template of my project.
I have already heard of template processors, but my problem is that I don't want to pass a variable to the base template, but to take it from the base template.
This is the piece of code that is placed in the base template. I need to access the user's input in the textarea and post it to the database.
<form method="POST">
<textarea id="comment" rows="10" cols="80"></textarea> <br>
<button type="submit">Send message</button>
</form>
Thank you very much in advance.

Related

Django: Update specific part of template by button click

I have a text field
<input type="text" value="This is a test." name="mytextbox" size="10"/>
and separated from that a button
<button type = "button" class="btn btn-primary">
<font size="1">Run</font>
</button>
that should update a list and update the value of the text field itself.
Sometimes forms are used in this context, but I would have to wrap the forms tag around the whole template when the input and button are separated on the screen.
Since I am relatively new to Django, I would like to know the best
strategy to solve the problem.
a) Reload the complete page template with changed arguments/context
b) Create a html template of the specific part that extends the main template and only try to render/update this one.
c) Do something smarter.
There are some answers in a (much older) post from 8 years ago but I am interested in the state-of-the-art solution.

How can I modify the basic Django template for SplitDateTimeField?

I have a simple SplitDateTime field:
meeting_datetime_start = forms.SplitDateTimeField(input_date_formats=["%a %d/%m/%Y"], input_time_formats=["%I:%M %p"])
This renders the following HTML:
<input id="id_meeting_datetime_start_0" name="meeting_datetime_start_0" type="text">
<input id="id_meeting_datetime_start_1" name="meeting_datetime_start_1" type="text">
I am using bootstrap, and want to add a custom template to render this HTML differently, such as:
<div class="col-xs-2">
<input id="id_meeting_datetime_start_0" name="meeting_datetime_start_0" type="text">
</div>
<div class="col-xs-3">
<input id="id_meeting_datetime_start_1" name="meeting_datetime_start_1" type="text">
</div>
How can I modify the basic Django template for the SplitDateTimeField?
You have some possible solutions.
1. Subclass SplitDateTimeWidget and redefine it's render method
By subclassing that widget you can inject into result code anything you want. After that just simply use your own widget with default SplitDateTimeField
2. Create inputs in template by hand
Possibly simplest solution, but most ugly in my opinion. Create code in template by hand, using proper variables for name, id, value etc. You must add _0, _1 suffixes and format existing value by hand.
3. Create template tag that will inject additional divs
You can create some template tag or filter that will do some text operations on default template to add additional divs.

Template Contexts not recognized from external file (Django)

So, I've been editing a website and have many JavaScript functions that utilize the Contexts that the views.py file passes to the page. Until now, these functions have been contained in the base.html file and so have been loaded onto every page directly. However, to make things cleaner, I copy and pasted all the functions to an external .js file. Now, rather than use the contexts, the functions consider them to be literal strings.
Example:
$('#title').text('{{ event.name }}');
The above line will actually set the text of the element to say "{{ event.name }}" rather than the name of the event. Any ideas on how to fix this? I really don't want to keep these functions in the base file where they can be seen by anyone who inspects the page source.
It doesn't matter if you put your javascript functions in an external file or in your base.html it would still get exposed to the user. Only a minification of the file would actually help to trick the user from seeing the actual values but with javascript all your code is public.
Why you're having this problem is because when you rendered the javascript inline (in your base.html) you had access to the template context.
This is no longer the case and the Django template engine doesn't interpolate your {{ event.name }} anymore.
The problem you're facing as well is a good one. You should never mix and match javascript with Djangos template language or any template language for that matter and the only way of fixing it is to
a) start pulling the values from the DOM ie. render a proper DOM
b) to start to fetch the values from the server, traditionally using AJAX.
And the smallest example that I can muster at the moment is below:
Your view:
def my_django_view(request):
return HttpResponse(json.dumps({'meaningoflife':42}), mimetype='application/json')
Your HTML
<input type="hidden" id="myMeaning" value="{{ meaningoflife }}" />
Your javascript
var meaning = document.querySelector('#myMeaning').value;
alert(meaning); //should alert 42.
In your view you return some form of render_to_response which takes a template argument and a context argument. What the render_to_response function does is read your template, and replace all {{ placeholders }} with the values passed via the context dictionary.
Templates are essentially a complex version of this
"""
<h1>{{ person.name }}</h1>
<p>{{ person.phone_number }}</p>
""".format(person)
The problem is the templating engine does not know files specified by a scripts src attribute is actually a Django template. To fix this don't use the script src attribute. Instead do something like this.
<!--base.html-->
<h1>Site Title</h1>
<p>Some content</p>
<script>
{% include 'jsfile.js' %}
</script>
Using the include statement should do the trick.

Refresh Only template Grails

I have a list.gsp which loads a template .
Actually the template contains which loads the data from the domain class.
Every 10 seconds I want to refresh the template only, so that it gets latest data from the db. How can i do this?
There are several ways to solve this but all of them require Ajax. I'll give one example:
Suppose the following HTML:
<div class="content">
... other content here
<div id="template">
<g:render template="someTemplate" ... />
</div>
... other content here
</div>
Then this javascript:
setInterval(refreshTemplateEveryTenSeconds, 10000);
function refreshTemplateEveryTenSeconds() {
$('#template').load("/some/server/resource");
}
See the jquery load docs for more info on this.
Obviously, if you're not using jQuery then modify to do the ajax call as your technology would suggest. But this gives you a general idea of how you might approach the problem.

Django Form Field Problems with Cloudinary's CloudinaryImage Class

I've got a Django form that is displaying a ClearableFileInput for a CloudinaryImage (from Cloudinary). Things are working great, except when I display the form field, I get a mangled href in the anchor element:
Currently: <cloudinary.CloudinaryImage object at 0x10b3f4ad0> <input type="checkbox" name="logo-clear" id="logo-clear_id" /> <label for="logo-clear_id">Clear</label><br />Change: <input id="id_logo" type="file" name="logo" class="span4" />
Here is the template code I am using:
<div class="fieldWrapper">
<label for="id_logo"><h3>{{ form.logo.label }}:</h3></label>
{{ form.logo|add_class:"span4" }}
<p>{{ form.logo.help_text }}</p>
</div>
The add_class part come from django-widget-tweaks. I've taken the add_class part out with no change in the output.
Here is my form definition:
class OrganizationFormTheme(forms.ModelForm):
pass
class Meta:
fields = ('logo',)
model = Organization
It looks like Django is having problems with the CloudinaryImage's url function. I suspect it is looking for a simple property rather than a function.
Any suggestions on how to handle this? Should I subclass CloudinaryImage and rewrite the url function somehow?
Indeed there was a conflict between the url function and the url property.
We've changed the function to be build_url instead of url.
In addition, you can specify transformation parameters as the url_options parameter when calling the constructor of CloudinaryImage. Then you can use the url property for getting the full Cloudinary URL.
The fix is available in the latest release of the Python library: http://pypi.python.org/pypi/cloudinary