Django nested ModelForm possible? - django-forms

Let's say I have a class Customer, with a nested class Address. Each customer has an address, and the customer table has a foreign key, address_id, that points to the address table. A customer can only have one address.
Is there a good way in Django to have an AddressForm nested inside CustomerForm, so that I can just send the CustomerForm to the template, and the framework will automatically display nested address fields, collect data for both classes, and save both on the back-end?
I tried reading the docs for this, and googling it, but most solutions talk about using Formsets and InlineFormsets, which seem to mostly be about having multiple inline instances, but in this case, there is only one nested class.
The way I am doing it now is to basically have the two separate ModelForm classes, send them separately to the same template, and then save them separately, which should work, but I wonder if there is a better, more elegant way.
Thanks in advance.

Related

Product slug not working in CRM 2013 Email templates

I have a business requirement that execs are really wanting to see. In our lead and email templates we have a few of our products listed. The products themselves are pretty stable but the prices are of course subject to change.
I'm OK with hard coding the product name into email but I was hoping the price could be a slug that get's resolved.
We only have one price list so nothing to worry about there.
I see no way to get access to the product and or price list entities through the data field values dialog.
So my thought was to create the 2-4 fields in the lead and opportunity entities. Then create a background workflow that takes the price from the price list and sets those fields.
Then when an email is generated I can access those hidden fields as they will be available through the lead or opportunity entity.
Any thoughts, concerns, better approaches?
Unfortunately CRM's email template system is not capable of what you describe out of the box. As you have discovered it will only permit you to insert placeholders from, or assocated with, the primary entity. It won't let you insert fields from other entities. What you suggest as a workaround is possible but it's not an ideal solution as you'll have these 2-4 redundant fields on each record type that contain duplicated data from the price list.
If you have any experience with creating custom workflow activities using the SDK then the best solution here is to create a custom activity that accepts either an draft Email or Email template as a input parameter, instantiates the email if required, loads the price list data, and performs your own custom placeholder replacements.
I've done this on a few projects in order to pass multiple entity records into the template, or to insert complex tables into emails by loading data from relationships. See the screenshots below for an example of how I've configured the email template and dialog process to pass both an 'Account' and 'User' record into the email template.

Changing the model's attributes - adding or removing attributes

I am working on a MVC3 code first web application and after I showed the first version to my bosses, they suggested they will need a 'spare' (spare like in something that's not yet defined and we will use it just in case we will need it) attribute in the Employee model.
My intention is to find a way to give them the ability to add as many attributes to the models as they will need. Obviously I don't want them to get their hands on the code and modify it, then deploy it again (I know I didn't mention about the database, that will be another problem). I want a solution that has the ability to add new attributes 'on the fly'.
Do any of you had similar requests and if you had what solution did you find/implement?
I haven't had such a request, but I can imagine a way to get what you want.
I assume you use the Entity Framework, because of your tag.
Let's say we have a class Employee that we want to be extendable. We can give this class a dictionary of strings where the key-type is string, too. Then you can easily add more properties to every employee.
For saving this structure to the database you would need two tables. One that holds the employees and one that holds the properties. Where the properties-table has a foreign-key targeting the employee-table.
Or as suggested in this Q&A (EF Code First - Map Dictionary or custom type as an nvarchar): you can save the contents of the dictionary as XML in one column of the employee table.
This is only one suggestion and it would be nice to know how you solved this.

Best approach on allowing users create their own fields

I'm about to embark on a project where a user will be able to create their own custom fields. MY QUESTION - what's the best approach for something like this?
Use case: we have medical records with attributes like first_name, last_name etc... However we also want a user to be able to log into their account and create custom fields. For instance they may want to create a field called 'second_phone' etc... They will then map their CRM to their fields within this app so they can import their data.
I'm thinking on creating tables like 'field_sets (has_many fields)', 'fields', 'field_values' etc...
This seems like it would be somewhat common hence why I thought I would first ask for opinions and/or existing examples.
This is where some modern schemaless databases can help you. My favourite is MongoDB. In short: you take whatever data you have and stuff a document with it. No hard thinking required.
If, however, you are in relational land, EAV is one of classic approaches.
I have also seen people do these things:
predefine some "optional" fields in the schema and use them if necessary.
serialize this optional data to string (using JSON, for example) and write it to text blob.

Correct way to map DTOs for complex pages

I have an MVC app and I have started to use DTOs exclusively to send data to views. I am using AutoMapper in order to ease this process.
Imagine I have a Customer that has many Orders. To display a simple customer overview page I can use AutoMapper with a simple DTO class that maps the Customer name, address etc. To map the orders I can AutoMapper a List<> of Customer.Orders to a more simple List<CustomerOrderDTO>.
I am now stuck on pages where I want both in the same view. Perhaps a simple headline with the customer name and phone number, then a list of orders. In some cases partials are the perfect solution, but not all.
So my question is how a DTO for a page such as this should look, and how that should be mapped (preferably using AutoMapper). In my research so far, I can't see how AutoMapper can map embedded enumerables like this.
when you create your mappings, ignore the collections/enumerables and just map simple objects to simple objects, for example CreateMap<Order, CustomerOrderDTO>()
when you execute the mapping, you can use collections and AutoMapper will just do the right thing, for example Map<IEnumerable<Order>, IEnumerable<CustomerOrderDTO>>()
if you're mapping an object contains the collection, for example Customer to CustomerDTO, where each one has it's collection of orders, as long as you've done CreateMap for the customer objects and CreateMap for the Order objects, the enumerable will just map automatically, unless you specifically set it to be ignored in the customer mapping.

Why Two Classes, View Model and Domain Model?

I know it could be bad to use domain models as view models. If my domain model has a property named IsAdmin and I have a Create controller action to create users, someone could alter my form and get it to POST a IsAdmin=true form value, even if I did not expose such a text field in my view. If I'm using model binding then when I committed my domain model, that person would now be an admin. So the solution becomes exposing just the properties I need in the view model and using a tool like AutoMapper to map the property values of my returning view model object to that of my domain model object. But I read that the bind attribute on a class can be used to instruct the Model Binder which properties it should and shouldn't bind. So what really is the reason for making two separate classes (domain model and view model) that essential represent the same thing and then incure overhead in mapping them? Is it more a code organization issue and if so, how am I benefiting?
EDIT
One of the most important reasons I've come across for a View Model that's separate from the Domain Model is the need to implement the MVVM pattern (based on Martin Fowler's PM pattern) for managing complex UIs.
I have found that while my domain model gets me 85% of the way to having the fields I want, it has never covered 100% of the values I want on my view. Especially when it comes to permissions and whether or not a user should have access to certain portions of the view.
The design concept I attempt to follow is to have as little logic in my views as possible. This means I have fields in my view model like "CanViewThisField" or "CanEditThisField." When I first started with MVC I would have my domain model be my view model and I was always running into the scenario where I needed just one or two more fields to make my view less cluttered. I've since gone the View Model/Model Builder route and it has worked wonderfully for me. I don't battle my code any longer but am able to enhance my view model as I need to without affecting the domain model.
Another good reason to have a ViewModel is paging large sets of data. You could pass the view an array of Person ( Person[] ) but metadata such as the number of pages, the number of the current page, the size of the page would not belong on the Person class.
Therefore a PersonListViewModel would solve this issue.
A ViewModel holds only those members which are required by the View. They can usually be thought of as a simplification or a "flattening" of the underlying domain model.
Think of them like this:
ViewModel: this is the data that is appropriate to render on this
view
Domain model: this is all the information my application needs
about this entity in order to perform all it's functionality
For example, my Order class has a member called Customer which is a composition association, that is, my Order has a Customer. This Customer object has members such as Firstname, Lastname, etc... But how would I show this on a "details" view of the order or a list of Orders and the Customers who placed them?
Well, using a ViewModel I can have an OrderListItemViewModel which has a CustomerName member and I can map the combination of Firstname and Lastname from the Customer object to this. This can be done manually, or much preferably using Automapper or similar.
Using this approach, you can have multiple Order ViewModels that are specific to different views, e.g. the Order list view might render the customer name in a different way to the Order details view.
Another advantage of ViewModels is that you can cut down on extraneous data not required of the underlying domain object on a view, e.g. if I'm viewing a list of orders, do I really want to see all the customer's contact information, billing details, etc...? I guess that depends on the purpose of the list but, probably not.
Sometimes you need to display the data in a specific manner (ie, displaying a date in the format mm/dd/yyyy vs. yyyy/mm/dd) and often it is easier to make this property in the view and not in the domain model, where you would (or should) have a mapping to a column in your db.
you need to remember
that your domain model classes are only used internally; that is, they are never sent to the
client. That’s what your service model types (View Model types) are used for—they represent the data that will be going back and forth between the client and your service.

Resources