Django Rest Framework render_form & required fields - css

When using HTML form renderer in DRF, can anyone think of a nice way to auto generate some indication of "required" field in DRF, by hook or crook? I mean before I submit the form, some indication on the field that it is required - the Browsable API it will show right in the form what the error is but only after submitting.
Whether I am using technique as shown here for browseable API with field level HTML forms (instead of just raw/JSON form):
django-rest-framework - autogenerate form in browsable API?
Or I am using TemplateHTMLRenderer with a call to render_form as discussed in docs here:
http://www.django-rest-framework.org/topics/html-and-forms/#rendering-forms
I don't see a simple way to make my required fields rendered as required. So say we have like
#models.py
class Foobar(model.Models):
foo = models.CharField(max_length=100, blank=True, default='')
bar = models.CharField(max_length=100, blank=False)
The best I can think of is making my own template/snippet for each type of field "required-text-field.html", "required-checkbox.html", etc and using the style declaration in the serializer as shown here:
http://www.django-rest-framework.org/topics/html-and-forms/#field-styles
That's assuming I am understanding this, have not played with it yet to see.
But I would love to see a way to auto-generate the field with/without a required flag as appropriate (even just an asterisk, or applying a CSS class) based on the model definition.
Rambling: The goal here was to avoid writing my own forms, having DRF generate the form for me in custom views. As opposed to writing my own forms using tying them into AJAX I figured templates, render_form, and some format checks would suffice. But now I'm thinking DRF is built for back-end and dev, not front-end, and maybe I should plan to write my own forms if it will be end-user visible? Also I could have CSS files and select based on name, calling render_form then applying hand spun styles, would be less work than the HTML + the CSS. Should I review Django (just Django, not DRF) Forms and re-use serializer as validation?...

I can see 2 ways:
you can define your own template pack, look at the existing ones in the sources (e.g. 'rest_framework/horizontal/input.html') - you can check if field is required and according to this flag, set some css. you do not need something extra, especially "input-readonly.html" - just make your own copy of input.html, add few if-s and it will work.
or you can call OPTIONS on the API endpoint to get all the necessary information about fields, not only required, but readonly and allowed values for some selects - this is if you can update your forms from javascript

Related

How do I tie a Drupal template to a webform with multiple environments?

Disclaimer: I inherited a Drupal 7.44 site with no experience in Drupal at all.
The business is trying to make a new webform and they want it to look exactly like an existing one. After looking around I found that the webform has a template tied to it. From the docs it seems I'm supposed to create more template files with the format webform-form-[nid].tpl.php where [nid] is the webform node id.
We have multiple environments that all changes must go through - dev, test, and finally prod. Wouldn't the node id be different in every environment for newly created webforms? Also, if I want to apply the same template to multiple webforms, do I really need to make multiple identical template files?
I also found some CSS styling for the existing webform and it looks like .webform-client-form-25 button.webform-submit and such. That 25 is the node id. I have little CSS experience, but this feels really bad. I don't want to copy blocks of CSS, changing node ids over and over. What's the proper way to assign generic, reusable CSS classes to webforms? I saw "Custom classes" under "Manage Display" when editing the form, but it didn't seem to change the actual HTML of the form. Was I on the right track though, should I just read some docs about it?
You are absolutely right, these detailed selectors do not make sense for reusable layouts.
Each webform HTML form gets a default class of .webform-client-form (that's generic) and an id including the webform's nid #webform-client-form-<nid>.
So, you could change #webform-client-form-25 to the class mentioned above. Please be aware, that this will affect all webforms then.
To set layout settings to several, but not all webforms, you need to give these webforms some class to distinguish them from the rest. Sadly, the Webform module itself doesn't provide an option to do that, but you can add a form alter hook in your theme's template.php:
function mytheme_form_alter(&$form, &$form_state, $form_id) {
$affected_forms = array('webform_client_form_25', 'webform_client_form_37', [...]);
if (in_array($form_id, $affected_forms)) {
$form['#attributes']['class'][] = 'my-custom-class';
}
}
With .my-custom-class you can then define CSS just for the group of webform forms listed in $affected_forms.
As for the template files, Webform itself states:
This file may be renamed "webform-form-[nid].tpl.php" to target a specific webform on your site. Or you can leave it "webform-form.tpl.php" to affect all webforms on your site.
So, again, it doesn't provide an option out-of-the-box, but you can create theme suggestions in your template.php by extending $vars['theme_hook_suggestions'] in a page preprocess function.

Registering an HTML-derived content type with the HTML editor without a package?

I'm trying to register a custom content type, similar to this question on MSDN forums: I want to register a custom extension that is essentially an HTML file, e.g.:
[Export]
[DisplayName("My Custom Markup")]
[Name("mycustom")
[BaseDefinition("html")]
internal static ContentTypeDefinition MyCustomContentType;
[Export]
[FileExtension(".mycustom")]
[ContentType("mycustom")]
internal static FileExtensionToContentTypeDefinition MyCustomFileExtensionDefinition;
So by specifying BaseDefinition as html, I am able to get HTML highlighting in .mycustom files, unfortunately I get nothing else, in particular, the HTML intellisense. From the above link it seems that the only way to have Visual Studio recognize custom extensions as a specific editor type, but I'd have to hack the registry (or more specifically, provide this via the ProvideEditorExtension attribute, but it's only applicable on a VSPackage).
So my question is, basically, is there an alternative way to register a custom extension to an editor programmatically, but without creating a custom VSPackage for it? Other than hacking the registry, of course?
(I could be totally wrong with the approach, in which case your help is very much appreciated!)
The easiest way is to use the technique demoed here:
http://blogs.msdn.com/b/noahric/archive/2010/03/01/new-extension-css-is-less.aspx
This is effectively "hacking the registry" but in a supported way. You're simply wrapping the needed keys in a .pkgdef file (essentially a .reg file) that can be contained in an editor extension.

How to get objects in a razor template in Tridion?

I am writing a common Razor TBB, which will use in Component Template and Page template as per my requirement.
So that, I need a Page and Component object in the razor TBB according to applying TBB on Page Template and component Template
My requirement to display/use the metadata field values from Page/Component in specific area of the page.
That's why, i want to access metadata values by the object but unable to get the object,
Please also follow-up my comments with Frank.
Can any one suggest me?
Did you have a look at the (remarkably helpful) documentation that is available for the Razor mediator?
http://code.google.com/p/razor-mediator-4-tridion/
http://code.google.com/p/razor-mediator-4-tridion/downloads/detail?name=RazorMediatorDocumentation_v1.2.docx
These are full of examples that access the current Component and the Page. Just my 10 second search gives these fragments:
<body class=”#Page.Metadata.BodyClass”>
<div class=”#Component.Fields.NewsStyle”>
<img src=”#Fields.HeaderImage.ID” alt=”#Fields.HeaderImage.AltText” />
Edit: I see you added some more details in your follow-up comment. You might want to do as Bart suggests and add those details to the question. In the meantime, I'll spend a few more minutes searching the documentation for you.
The official documentation (the Word document I linked above), contains this example that seems to process metadata:
#foreach (var keyword in Publication.MetaData.SomeKeywordFields) {
<li>#keyword.Title (#keyword.Id)</li>
}
The output of the Razor template will become the Output item in the Package. So it doesn't make any sense to use a Razor mediator to process the Output item. For that you might as well use a regular C# (fragment or assembly) TBB.
Another edit: It seems that the Razor mediator's implicit Fields variable always maps to the Component fields and the Metadata variable always maps to the Component's meatadata fields. I've linked the above names to the relevant fragments on Google code for your convenience.
So you seem to have two options:
detect whether you are in Page or Component (e.g. by looking at whether the implicit Page variable is null or not) and then have conditional expressions everywhere (isInPage ? Page.Metadata : Metadata)
fix this limitation of the Razor mediator code yourself or hire someone to fix it for you

Drupal views add form to add record

I have some view which lists my module table entries.
What is the most elegant way to attach a form below the view to add record?
Waht I am trying to do know is:
I created dedicated form in my module:
function my_module_form_add_record($form_state) {
form fields.....
}
I added to the view theme file:
$add_form = drupal_get_form('my_module_form_add_record');
print $add_form;
But I do not like this solution for at least 2 reasons:
I does not work ...
2. Even if it worked - it is depended on the theme file! So if I change the theme - functionality is crashed.
I would like to find more elegant solution to attach form from custom module to the view.
I know of the existence of the "Views Attach" module but it has no option of adding custom forms.
I know also of the existence of the Views Embedded form (and I am usig it) but it is only useful if you want to add form to the every row.
Seems the must be some solution to add record from the view page!
Thanks you for help.
you could use hook_views_pre_render:
This hook is called right before the render process. The query has been executed, and the pre_render() phase has already happened for handlers, so all data should be available.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

How to create custom CSS "on the fly" based on account settings in a Django site?

So I'm writing a Django based website that allows users select a color scheme through an administration interface.
I already have middleware/context processors that links the current request (based on domain) to the account.
My question is how to dynamically serve the CSS with the account's custom color scheme.
I see two options:
Add a CSS block to the base template that overrides the styles w/variables passed in through a context processors.
Use a custom URL (e.g. "/static/dynamic/css/< website_id >/styles.css") that gets routed to a view that grabs all the necessary values and creates the css file.
I'm content with either option, but was wondering if anyone else out there has dealt with similar problems and could give some insight as to "Best Practices".
Update : I'm leaning towards option number 2, as I think this will allow for better caching down the road. So it's dynamic the first time, gets stored in memcache (or whatever), and invalidated when a user updates their settings in the admin site.
Update: Firstly, I'd like to thank everyone for their suggestions thus far. All the answers thus far have focused around generating static files. Though this would work great in production, it feels like a tremendous burden during development. If I wanted to add a new element to be styled, or tweak existing styles I'd have to go through and recreate each and every css file. Sure, this could be done with a management command, but I just don't feel it's worth it. Doing it dynamically would add 1 maybe 2 queries to each page load, which is something I'm not worried about at this stage. All I need to know is that at some point I will be able to cache it without rewriting the whole thing.
I've used option #2 with success. There are 2 decent ways of updating the generated static files that I know of:
Use a version querystring like /special_path.css?v=11452354234 where the v parameter is generated from a database field, key in memcached, or some other persistent file. Version gets updated by admin, or for development you would just make the generation not save if the parameter was something special like v=-1. You'll need a process to clean up the old generations after some time.
Don't use a version querystring, but have it look first for the generated file, if it can't find it, it generates it. You can create a cron job or WSGI app that looks for filesystem changes for development, and have a hook from your admin panel that deletes generations after an update. Here's an example of the monitoring, which you would have to convert to be specific to your generations and not to Django. http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Monitoring%5FFor%5FCode%5FChanges
Could generate the css and store it in a textfield in the same model as the user profile/settings. Could then have a view to recreate them if you change a style. Then do your option 1 above.
Nice question.
I would suggest to pre-generate css file after colors scheme is saved. This would have positive impact on caching and overall page loading time. You can store your css files in directory /media/css/custom/<id or stometing>/styles.css or /media/css/custom/<id or sth>.css and in template add <link rel="stylesheet" href="/media/css/custom/{{some_var_pointing _to_file_name}}" />
You can also do the trick with some random number or date in css file name that could be changed each time file is saved. Thanks to this browser will load the file immediately in case of changes.
UPDATE: example of using model to improve this example
To make managing of those file easy you can create simple model (one per user):
class UserCSS(models.Model):
bg_color = models.CharField(..)
...
...
Fields (like bg_color) can represent parts of your css file. You can ovveride save method to add logic that creates css file for user (by rendering some template).
In case your file format change you can make changes in your's model definition (with some default values for new fields), make little changes in template and run save method for each exisintg instance of class. This would renew your css files.
That should work nicely.
I would create an md5 key with the theme elements, store this key in the user profile and create a ccs file named after this md5 key : you gain static file access and automatic theme change detection.

Resources