django queryset and templates - django

I am quite new to django, and I have built a small page using forms.
When I go to the template and use the template tags, such as:
{{form.q}}
everthing is fine, and I see the form input field. However, I do not really like the input "box" it provides and I want to override this feature.
So, in my HTML, I would have something like:
<input id="customfield" name="q" type="text"/>
I tried the above, and everything seems to work fine. However, if I use for example:
<input id="customfield" name="{{form.q}}" type="text"/>
it dosent work. So, my question is:
[1] Is it ok to use name="q" or how can one specify {{form.q}} if I have a custom input?
[2] Are there any disadvantages (like sql injection) when using name="q" as opposed to simply using {{form.q}}?
Sorry for the 101 questions!

This is exactly how you would build a form if you wanted this much control in the template.
You'd take this course when other django shortcuts have failed, like one of the build in widgets that determine the way your field is rendered.
Update: after reading your comment, if you just want to inject attributes to the input element, you can pass the widget a dictionary containing attribute:value pairs.
q = forms.CharField(widget=forms.TextInput(attrs={'class': 'foobar'}))
SQL injection is irrelevant here (you'd worry about this when a user has something to do with SQL written on your server) and there are no disadvantages, aside from the code being more difficult to write and maintain.

Related

Auto-Expanding TextAreas on PDF Generated from Django Template

I'm using pdfkit to generate a PDF of a Django template (doing this by getting an HTML string of the page from Django's get_template and render functions and passing that string to pdfkit... see post).
On this page, I have some TextArea's that can contain many lines of text, and by default, they just get cut off when generating the PDF.
I've tried to fix this by using some javascript libraries (I've tried several) to automatically expand the TextAreas on page load. I can get these to work perfectly on normal pages, but when I try to include it on the PDF template, I get various errors ranging from not working at all to expanding the TextArea way too much. My first assumption was that there was some styling differences that were causing the issues, but I'm fairly certain I've ruled that out. I tried to load the PDF template directly as a view, and the TextArea's resized correctly, leading me to believe that there's something with pdfkits generation that isn't playing nicely with the resizing.
Given this, I tried to look if pdfkit has any suggestions for issues like this and couldn't find any, and I also tried to use different input types other than TextAreas, none of which were able to display newlines correctly.
I can't think of any other potential solutions at this point, and I'm open to suggestions. Please let me know if you feel I should provide additional information, and thank you in advance.
I ended up finding a relatively simple fix. Because I was using django forms, I was pretty easily able to change from displaying the form Textarea:
{{ form.paragraph_data }}
to displaying just the plain text:
{{ form.paragraph_data.initial }}
However, this initially caused the newlines to not display correctly, because HTML doesn't process them in a plain string. So I added some processing in the creation of the form to replace the newlines with <br />s:
form.fields['paragraph_data'].initial = form.fields['paragraph_data'].initial.replace('\n', '<br />')
Finally, I had to add the safe filter to Django templating line to tell it to actually render the HTML rather than cleansing it:
{{ form.paragraph_data.initial|safe }}
Again, this was partially easy because of Django forms, but it should translate relatively easily to a more standard javascript/html solution.

Use Django templates to generate forms

I’m planning to use the Django templating system in a slightly uncommon way. I need an app that will let me easily create simple “fill in the gap”-style forms and I decided to use Django templates with custom tags to design the forms.
Here is a sketch of what I mean:
<p>
This is the <i>form</i>. Two plus two is {% gap four 4 vier %}.<br>
The best programming language is {% case_gap Python Haskell %}.
</p>
{% if all_correct %}
You are smart.
{% else %}
<input type="submit">
{% endif %}
The idea is that the *gap tags render a text input control, look into the context to see if the answer for them was sent, and if the answer is correct, mark the text inputs green.
The question is how to implement the all_correct logic. The simple solution is to add this variable to the context and then make each *gap tag update it based on its correct answer, and, I believe, this should work with my example. But what if I want to move the {% if all_correct %} code to the top of the template, where none of the gaps were rendered, and thus none of them have validated their answers yet?
Looks like I need some way to iterate over all the *gap tags before starting to render the template and [ask them to] validate the answers, but I don’t know the internals of the templating system well enough to implement this. Or there might be a completely different and better way.
I believe I figured how to do this after reading Chapter 9 of The Django Book.
Creating of a custom template tag involves defining of two things: how to compile the tag and how to render it. The compile-function should parse the tag data and return a Node—basically a thing that has a .render(self, context) method and some other data derived from the tag text.
The solution is to create FormNode—a subclass of Node that will also have a .validate(self, context) method. Then our custom tag will be compiled to a subclass of FormNode that implements validation logic.
The next thing to do is to create FormTemplate—a subclass of Template with a super-power: before starting to render individual nodes it will validate all the nodes by iterating over them and calling validate(context) on all the subclasses of FormNode and it will set the all_valid variable in the context.
Here is my proof-of-concept implementation: https://github.com/kirelagin/django-template-forms. I believe it works pretty well.
I used the ability to instantiate a custom template engine, which was added in Django 1.8. Overall, I had to dig a little deeper than one might expect and I always had this feeling that splitting of the templating API and the django engine (which is now just one of the available backends) wasn’t complete yet. I hope that Django 2.0 will bring us new cool stuff and all the hacks I had to add will vanish.

Advice on WYSIWYG architecture for an Ember app

I'm having a hard time coming up with a solution for this problem.
I'm building a WYSIWYG designer, for micro sites. The templates for these microsites will be supplied by an intermediate user, and the end-user will manipulate these templates. So, there are really two groups of users of the app: template-buiders, and end-users. Think MailChimp.
This means my Ember app will start off with a template from a template-builder, say
<h1>An awesome product</h1>
<h2 contenteditable="true">Subtitle away</h2>
<p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>
and the end user, having chosen this template, will then be able to customize it. There are a few requirements:
There will be static, uneditable portions of the page (h1 above)
There will be static, editable portions of the page (h2 above)
There will be options that affect the layout, style, etc. (p above)
So far, my attempts have lead me to build a handlebars helper that takes a string and a context, and returns a rendered template. This is because the above template will actually be coming over from a database, as a string - remember, it's user-generated.
That means, in my application's template, it would look like
<div class="preview">
{{preview-userTemplate template context}}}
</div>
where
template: '<h1>An awesome product</h1><h2 contenteditable="true">Subtitle away</h2><p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>',
context: {optionA: true}
Now, this actually works, in the sense that it will update if context is updated, so I can add controls along the sides for the end-user to manipulate those options. So I have those (more of less) under control.
It's the WYSIWYG content editing that is giving me trouble. In the above template (from my template-builder users), I want them to be able to add contenteditable="true" to places in their templates where the end-users can change the content.
Now, these changes need to be saved. Ideally, I would be able to retrieve the instance view's template back from the DOM, after the inline edits have been made. Is this possible? The original {{data}} placeholder would need to be preserved.
Alternatively, I could make a view/component, so the template-builder would do something like this:
<h1>An awesome product</h1>
{{#editable}}
<h2>Subtitle away</h2>
{{/editable}}
<p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>
but this seems like it would require a good deal of finagling to get the edits to stick - I'm not even sure right now how I'd go about it.
What do you guys think? Is there an easier solution that I'm overlooking? Thanks for any pointers!

Creating normal forms in Joomla 2.5

I want to create a simple registration form as one of the pages in my Joomla 2.5 website.
Every where on the internet, I see people asking me to use an extension like proforms, ckforms etc.. Most of the have price tags on them and the free ones do not have database and I don't really want a lot of functionality.
I just want the following code to work. So that I can pull the POST variable and insert them in a db.
<form method="post" action="mycreatedpage.php">
<input type="text"/>
<input type="submit">
</form>
Is this not possible in Joomla 2.5?
After a bit more searching, I realized that what I really needed was an ability to make PHP run inside the article. Thanks to a video.
Answer :
Install Sourcerer to enable PHP inside joomla articles
Create an article which take in the POST variable and insert into the database. This is the tricky part. What I did here was take the general PHP code which I would have written in register_do.php and insert it using the Sourcerer plugin.
Now create an menu Item which points to the above article. Save the menu item and copy the alias. This alias will be the action for the form.
From here on on, everything must work fine.
For more detailed instructions, watch the video
When you post a form, you have to have some code to handle the form input and what to do with it. So your options are to write a component to handle that form input or to use a form component that does it for you. If you write your own there is a lot to consider unless you want to open up gaping security holes in your website.
There are plenty of free forms components available. If you want free, I would recommend Chronoforms, if you don't mind paying small fee then RS Forms.

Is it a common practice to wrap all page content in a form inside a top-level template?

There is a top-level template in my project and it defines several sub-templates nested in a form:
<h:form>
<ui:insert name="header"/>
<ui:insert name="leftbar"/>
<ui:insert name="maincontent"/>
</h:form>
It's not my idea actually to build application in this way. I see both its advantages and disadvantages.
The biggest problem I've met is necessity of 2 forms on 1 page: first with default enctype and second for uploading files. The second biggest problem is validating unnecessary fields (but it can be relatively easily solved by disabling validation on those fields with jstl c:if).
I'm using JSF and Facelets currently but the described design is possible with any templating framework.
So, what I wanted to ask: how do you think is it worth to use this wrapper-form? Is is a common practice?
It certainly is not. You're now using one "super-form" for all actions in the page. This is not the common practice. Every related group of input elements should be placed in its own form. You don't want to validate/submit your contact form in the main content if you submit the search form in the header.