I have written a python app which as a result creates a list of Result objects. I've written a method which makes a html representation of the object Result, showing its main attributes.
class Result():
def to_html(self):
num_of_exp = "Number of exponentials: %s"% self.number_of_exponentials
function = "Function: %s"% self.function
par_of_exp = "Parameters of exponentials: <br /> %s "% pprint.pformat(self.parameters_of_exponentials)
chunk = "Chunk: <br /> %s"% pprint.pformat(self.chunk)
backgrnd = "Background <br /> %s" % pprint.pformat(self.background)
raw_par_of_exp = "Raw parameters of exponentials: <br /> %s"% pprint.pformat(self.raw_parameters)
non_phy = "Non physical solution: %s" % pprint.pformat(self.non_physical_solution)
user_choice = "User choice: %s" % pprint.pformat(self.user_choice)
output = (function + r"<br /><br />" + num_of_exp + r"<br /><br />"+ par_of_exp + r"<br /><br />" +
backgrnd+ r"<br /><br />" + non_phy + r"<br /><br />"
)
return output
I'm using Django to make a web interface for the application.
I made a Django template:
...
<body>
{% for result in result_list %}
{{result.to_html}}
{% endfor %}
</body>
And added
return render_to_response('result_pick.html',{'result_list': rp.parsed_output_data })
where rp.parsed_output_data is a list of Result objects (the size of the list is not fixed).
The output i get completely ignores the html tags in to_html(). Html source of the output:
Function: 98.627732*2.71828182845905**(-0.016052058*t)<br /><br />Number of exponentials: 1<br ... ...
What i have to get as a final result are representations of Result objects displayed in a nice human readable format, each in its own divs and form with a next button. So when the user selects a Result he is transfered to another page where additional details are shown.
I'm looking for advices on how to do this the right and most clean way. Any comment is appreciated. Tnx
Html tags are ignored / autoescaped for safety see here and here.
The right way would be constructing html output through django templating system and not within object itself e.g.:
<body>
{% for result in result_list %}
Function: {{ result.function }}<br /><br />
Number of exponentials: {{ result.number_of_exponentials }}<br /><br />
...
{% endfor %}
</body>
Related
i'm trying to pass values as parameters using url_for but i have some problems as i have first some data loaded by a function and then, some data inserted manually using the <input ../> constructs. How can I do?
<td align = "center"> <a href = "{{url_for ('insertResults', idGia = attribute [0], language = attribute [4], level = attribute [5], info = info, written = written, oral = oral, session = session)}} "type =" submit "class =" btn btn-primary "> Insert </td>
where info, written and oral are the data entered as input in the following ways:
<td align = "center"> <input type = "text" placeholder = "100" id = "info" name = "info" /> </td>
<td align = "center"> <input type = "text" placeholder = "100" id = "written" name = "written" /> </td>
<td align = "center"> <input type = "text" placeholder = "100" id = "oral" name = "oral" /> </td>
The url_for function is executed on the server side. It is not possible to pass parameters from form fields to this.
Are you sure you want to use a GET request for this? It seems to me that a POST request makes more sense in your situation.
The following example shows you different methods with which you can transfer variables with a POST request and query them within your route. The data largely find their place within the request body. Only the attribute with the name "attr0" is sent within the url.
<form action="{{ url_for('indert_results', attr0=attr[0]) }}" method="POST">
<input type="hidden" name="val0" value="{{ attr[1] }}" />
<input type="text" name="val1" />
<input type="text" name="val2" />
<button type="submit">Submit</button>
</form>
#app.route('/insert-results/<int:attr0>', methods=['POST'])
def insert_results(attr0):
val0 = request.form['val0']
val1 = request.form.get('val1')
val2 = request.form.get('val1', 'default-value1')
print(
f'attribs: {attr0}',
f'values: {val0}, {val1}, {val2}',
sep='\n'
)
# ...
If you do insist on a GET request, I still advise you to use a form so that you can transfer the entries from the form fields as query parameters.
All data is transmitted in different sections of the url. The query parameters are added to the url in the form "?param0=value0¶m1=value1".
<form action="{{ url_for('insert_results', attr0=attr[0], attr1=attr[1]) }}" method="GET">
<input type="text" name="param0" />
<input type="text" name="param1" />
<input type="text" name="param2" />
<button type="submit">Submit</button>
</form>
#app.route('/insert-results/<int:attr0>-<str:attr1>', methods=['GET'])
def insert_results(attr0, attr1):
param0 = request.args['param0']
param0 = request.args.get('param1')
param1 = request.args.get('param2', 'default-value2')
print(
f'attribs: {attr0}, {attr1}',
f'params: {param0}, {param1}, {param2}'
sep='\n'
)
# ...
Regardless of whether you use the form or ask for the arguments within the url, you use a kind of dictionary which allows you to use .get(key [, default] [, type = <func_ptr>]) to ensure that a KeyError is bypassed, a default value is passed and possibly the type of the value is converted.
Choose the transmission method wisely and consider the visibility of the data for third parties, taking into account that the transmission may later take place in encrypted form. You should also consider the amount of data you want to send. The more data you want to transfer, the sooner you will switch to a POST request.
Especially with several data records that are transmitted individually, you can later think of a transmission using ajax. However, this is a more complex solution and the explanation would lead too far at this point.
How do I invoke the upload widget outside Admin?
Using the standard form below does not work. The widget is corrupted.
forms.py
class PhotoAdd(forms.ModelForm):
class Meta:
model = Photo
fields = ('ImageFilerField',)
views.py
def photoadd(request):
context={}
context['form'] = PhotoAdd()
render(request, 'template.html', context)
template.html
{{ form }}
There is absolutely no reference to this in the documentation.
How can I upload photos outside admin?
Edit: (added generated code from django above)
<label for="id_doc_pic">Doc pic:</label>
</th>
<td>
<span class="filerFile">
<img id="id_doc_pic_thumbnail_img" src="/static/filer/icons/nofile_48x48.png" class="quiet" alt="no file selected" />
<span id="id_doc_pic_description_txt"></span>
<a href="/admin/filer/folder/last/?_to_field=file_ptr" class="related-lookup" id="lookup_id_doc_pic" title="Lookup">
<img src="/static/admin/img/icon_searchbox.png" width="16" height="16" alt="Lookup" /></a><img id="id_doc_pic_clear" class="filerClearer" src="/static/admin/img/icon_deletelink.gif" width="10" height="10" alt="Clear" title="Clear" style="display: none;" /><br />
<input class="vForeignKeyRawIdAdminField" id="id_doc_pic" name="doc_pic" type="text" />
<script type="text/javascript" id="id_doc_pic_javascript">
django.jQuery(document).ready(function(){
var plus = django.jQuery("#add_id_doc_pic");
if (plus.length){
plus.remove();
}
django.jQuery('#id_doc_pic_javascript').remove();
});
</script>
</span>
Javascript Error: "Uncaught ReferenceError: django is not defined"
Could it be that I need to know what css to include and what javascript files to load?
First of all, add {{ form.media }} in your html file, just after the tag <form> and {% csrf_token %}. Then extend the media class in your ModelForm of forms.py as explained by SteinRobert on Github issue: https://github.com/divio/django-cms/issues/6028. It works perfect! Thanks Stein!
I've become very frustrated by a problem I'm having. I have a large form that's hand-written (not using Django's forms), and am simply trying to access the data from the inputs in the views (in that case, some inputs were posting, others weren't).
Leaving the specifics of that form aside for now since there are too many things at play, in my troubleshooting process I wrote the simplest form I could think of, and am now getting no POST data besides the csrf_token.
I have no idea why this would be, since something similar (and much more complex) works fine on several other django projects I'm running. For this example, I tried with action="" as well to no avail. Is there something incredibly obvious I'm missing?
Here's the html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST" id="theForm" action="/simpleForm/">{% csrf_token %}
<input type="text" id="theText" value="Where am I?" />
<input type="hidden" id="hiddenInput" value="I don't exist" />
<input type="submit" />
</form>
</body>
</html>
Here is a simple view checking for data:
from django.shortcuts import render
def simpleForm(request):
if (request.method == 'POST'):
print('In post')
print(request.POST)
for i in request.POST.keys():
print('key: {0} value: {1}'.format(i, request.POST[i]))
return render(request, 'simpleForm.html')
else:
return render(request, 'simpleForm.html')
You're missing the 'name' attribute of the tags in your HTML form. Without those, Django will not add them to request.POST
<form method="POST" id="theForm" action="/simpleForm/">{% csrf_token %}
<input type="text" id="theText" name="mytext" value="Where am I?" />
<input type="hidden" id="hiddenInput" name="myhidden" value="I don't exist" />
<input type="submit" />
[Edit: See my answer below - the origin of this issue is invalid markup, and browsers working very hard to hide that. ]
I have a formset which definitely should contain two forms, but for whatever reason, I am only getting one form printed in the template.
This is the template line:
<tr id="existing_docs_row"><td colspan="2">{{ existing_articles.management_form }}{% for f in existing_articles %}<div>{{ f }}</div>{% endfor %}</td></tr>
I get the exact same behaviour (less div tags) with:
<tr id="existing_docs_row"><td colspan="2">{{ existing_articles }}}</td></tr>
The management form and first form are created, but not the second. This is what I get in my browser:
<input type="hidden" id="id_form-TOTAL_FORMS" value="2" name="form-TOTAL_FORMS"><input type="hidden" id="id_form-INITIAL_FORMS" value="2" name="form-INITIAL_FORMS"><input type="hidden" id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS"><div><div class="selected_row " id="selected_row"><span class="formlabel"></span><ul>
<li><label for="id_form-0-selected_0"><input type="radio" name="form-0-selected" value="True" id="id_form-0-selected_0"> </label></li>
</ul></div>
<div class="original_filename_row " id="original_filename_row"><span class="formlabel"><span id="for-id_form-0-original_filename-">Original filename:</span></span><div id="id_form-0-original_filename" name="form-0-original_filename">FakeExampleCompanyName.docx</div></div>
<div class="tags_row " id="tags_row"><span class="formlabel"><span id="for-id_form-0-tags-">Tags:</span></span><div id="id_form-0-tags" name="form-0-tags" class="tagarea"><span class="tagitem">England and Wales</span> <span class="tagitem">Private company limited by shares</span> <span class="tagitem">Model articles with amendments</span></div></div>
Breaking in the view, and printing the formset shows that it contains two forms (existing_template_formset is the name of the formset inside the view):
>>> print existing_template_formset <input type="hidden" name="form-TOTAL_FORMS" value="2" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
<div id="selected_row" class="selected_row "> <span class="formlabel"></span><ul> <li><label for="id_form-0-selected_0"><input type="radio" id="id_form-0-selected_0" value="True" name="form-0-selected" /> </label></li> </ul></div> <div id="original_filename_row" class="original_filename_row "><span class="formlabel"><span id="for-id_form-0-original_filename-">Original filename:</span></span><div name="form-0-original_filename" id="id_form-0-original_filename">FakeExampleCompanyName.docx</div></div> <div id="tags_row" class="tags_row "><span class="formlabel"><span id="for-id_form-0-tags-">Tags:</span></span><div class="tagarea" name="form-0-tags" id="id_form-0-tags" ><span class="tagitem" >England and Wales</span> <span class="tagitem" >Private company limited by shares</span> <span class="tagitem" >Model articles with amendments</span></div></div> <tr><th></th><td><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>
<div id="selected_row" class="selected_row "><span class="formlabel"></span><ul> <li><label for="id_form-1-selected_0"><input type="radio" id="id_form-1-selected_0" value="True" name="form-1-selected" /> </label></li> </ul></div> <div id="original_filename_row" class="original_filename_row "><span class="formlabel"><span id="for-id_form-1-original_filename-">Original filename:</span></span><div name="form-1-original_filename" id="id_form-1-original_filename" >FakeExampleCompanyName.docx</div></div> <div id="tags_row" class="tags_row "><span class="formlabel"><span id="for-id_form-1-tags-">Tags:</span></span><div class="tagarea" name="form-1-tags" id="id_form-1-tags" ></div></div> <tr><th></th><td><input type="hidden" name="form-1-id" id="id_form-1-id" /></td></tr>
>>> len(existing_template_formset) 2
As you can see, in both cases, the total number of forms in the formset is 2 (as evidenced in the management form), but the second one is simply not generated.
Has anyone come across this before? How do I fix this?
I'm using django 1.3.1 on python 2.7.2 on windows.
For completeness, here is the code which creates the formset:
class ExistingTemplateFormset(modelformset_factory(ArticlesTemplate, extra = 0, form=ExistingTemplateForm)):
def __init__(self, *args, **kwargs):
super(ExistingTemplateFormset, self).__init__(*args, **kwargs)
for x in self:
x.fields['id'].widget = forms.HiddenInput()
x.fields['original_filename'].editable = False
x.fields['original_filename'].widget = SpanWidget(tag = u'div')
x.fields['tags'].widget= TagArea()
x.fields['tags'].help_text = u''
(TagArea and SpanWidget exist)
In the view:
existing_template_formset = ExistingTemplateFormset(queryset = the_organisation.get_template_articles())
Sharp-eyed readers (which, it turns out, does not include me, hence this problem) will note that my output includes at the end of each form:
`<tr><th></th><td><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>`
Now, when that is substituted into <tr id="existing_docs_row"><td colspan="2">{{ existing_articles.management_form }}{% for f in existing_articles %}<div>{{ f }}</div>{% endfor %}</td></tr> that leads to invalid markup (a tr inside a tr!).
So, it turns out that the template was generating the second form, but the browser's error recovery methods (in chrome, disregarding a lot of the invalid markup; in firefox, floating the second form to elsewhere in the DOM) created the appearance that the second form wasn't being generated.
To summarise: just examining the DOM mislead me. Try to force your browser to choke on errors, and look at the raw markup.
I have an pre-built HTML form and I need to reuse it with Django form class (django.forms), So how do I incorporate my HTML form with Django form class. for example
HTML:
<li id="foli11" class="">
<label class="desc" id="title11" for="Field11">
Username
<span id="req_0" class="req">*</span>
</label>
<div class="col">
<input id="Field11" name="Field11" type="text" class="field text medium" value="" maxlength="255" tabindex="11" />
</div>
</li>
How do I map this HTML in to Django form class, I know that it can be done by modifying Django form fields according to this HTML. But I guess it's a time consuming approach,so I would like to know that is there any easy and time saving solutions for this issue.
Thanks.
Extend the django forms.Form class and write to it your own form.as_my_ul similar to form.as_p:
Here is the implementation of as_p: http://code.djangoproject.com/browser/django/trunk/django/forms/forms.py#L227
def as_p(self):
"Returns this form rendered as HTML <p>s."
return self._html_output(
normal_row = u'<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
error_row = u'%s',
row_ender = '</p>',
help_text_html = u' %s',
errors_on_separate_row = True)