Django save model and its children with ModelForm - django

I have such models: Article, Link & ArticleLink. Article can have many links attached to it and I need to save them from one form.
I have created all the relations and a ModelForm for Article, but the trick part is that links have two fields: Name and URL. I can't figure out what kind of form structure must be used, I tried hidden inputs with name "links[name]" and "links[url]" but did not work.
Where should I look? Is there any working example for this? Django docs does not help with this particular situation.

You should take a look at inline formsets.

Related

Creating Model Relationships Via Forms

What is the defacto way of creating model relationships in Django via frontend forms.
For example a user signs up for service using a form, they start a quote.
In getting a quote they can select and add products to their quote specifying variable such as sizes in this process.
This is modelled with relevant User, Quote, Product models and relevant relationships.
I am trying to work out the best way that these are linked together by frontend forms and views.
Would I load into the quote form a hidden field for the related user_id for example, which I can then process manually to form the one-to-many relationship.
I am just wondering if this is something accounted for within forms or if I have to manually create the forms to achieve my goal.
This is one of the more complicated things to try and achieve but there are several things in Django which will help you.
You're going to need a ManyToMany field on the Quote model to link the Products to it.
This can be displayed in forms simply via a ModelMultipleChoiceField:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelmultiplechoicefield
... which is just renders a basic multiple select list of existing products.
The interface you want probably looks more like an inline formset however. The complication here is that they are designed for ForeignKey relations rather than ManyToMany.
Under the covers, a ManyToMany relation is actually just two ForeignKey relations, via an intermediate 'through' model. We can exploit this to build an inline formset on the through model, see this answer:
https://stackoverflow.com/a/10999074/202168
You'll note the caveat in that answer, the inline rows won't know which Quote they belong to unless you override some code.
You may like to look at some helper apps which provide custom widgets for ManyToMany fields:
https://code.google.com/p/django-ajax-filtered-fields/
http://django-autocomplete-light.readthedocs.org/en/latest/

Django app where you can send application to authorities

I am currently working to write a web app where people fill out the necessary information, and apply to their mentors.
So, at this point, mentors have a model class that is pretty much like the applicant's, so that they can correct the applicant's info without affecting the applicant's original profile.
I will appreciate any helpful comments. Specifically, I am looking for:
-A similar per-exisiting django app that does more or less so I can browse the source.
-Any special Django feature that allows this that I can not aware of.
-General info on how things like these are done in general.
Thank you.
Ad general info)
You would benefit from doing this in a single model (say ApplicationModel), with fields in pairs - field_name_applicant, field_name_mentor.
Then use a CreateView with its fields property set to only the *_applicant fields for the applicant to fill in the applications initially, and an UpdateView with its fields set to the *_mentor fields for the mentor to correct the applicant fields.
Have ApplicationModel.clean() copy all *_applicant field values to their *_mentor counterpart if the later is not set.
Now you have all your business logic in the model where it belongs; quoting a headline in the introduction of Two Scoops of Django:
Fat Models, Helper Modules, Thin Views, Stupid Templates

When to use form vs model validation?

Just curious. What is the best practice for when to use form vs model validation?
From what I understand currently, form validation should be used for:
AJAX / HTTP requests params
Forms that do not correlate to a model?
Another question is: I have a HTML form that roughly correlates to a model instance, do I use a ModelForm for it?
Definitely use ModelForm, if your form resembles model object even in a tiny bit.
If there are some minor differences (e.g. you don't use some of the fields or you want to use different error messages etc.) it's much easier to customize ModelForm then to use Form and implement all this functionality from scratch.
For more reference regarding ModelForm please checkout PyDanny's Core Concepts of Django ModelForms.
I am also trying to understand what is the difference/relation between form and model validation and I would like to share my notes that are formed after reading several docs.
I am currently interested in Creating Forms from Models
#mariodev shared the document Core Concepts of Django ModelForms and this provided a good start.
ModelForms select validators based off of Model field definitions
The main story behind the scenes seems to be the DRY principal. This article explains very well what exactly is the case here.
All right, all this is fair. The question is "Where in the Django Documentation is this explained"?
I bumped on a very brilliant article where it states that:
The form.full_clean() method is called by django at the start of the validation process (by form.is_valid(), usually immediately after the view receives the posted data).
Correct me if I am wrong but that line reads that everytime I enter data and hit 'enter' the validation process begins!
OK, this is simple now:
The validation on a ModelForm begins when we hit 'enter'.
Django first validates the form by checking one by one every applicable validation method on Fields, Field Subclasses (This is the documentation for a model's field subclass, not for a form field subclass), Form Subclasses and ModelForm (since it is a ModelForm).
Finally, it validates the Model Instance.
This is how all this works theoretically. The only thing that remains is to implement it.

Django: "reverse" many-to-many relationships on forms

The easiest example of the sort of relationship I'm talking about is that between Django's Users and Groups. The User table has a ManyToMany field as part of its definition and the Group table is the "reverse" side.
A note about my constraints: I am not working with the Admin interface at all nor is that an option.
Now, onto the programming problem. I need to write a form that is used to edit MyGroup instances, defined simply as the following:
class MyGroup( Group ):
some_field = models.CharField( max_length=50 )
I want to be able to have a form page where I can edit both some_field and which users are members of the group. Because I'm working with a model, a ModelForm seems obvious. But I cannot figure out how to get Django to include the users because it is on the reverse side of the User-Group relationship. Ideally, I'd like the display widget for specifying the users to be like the one for specifying permissions that is found on the User and Group pages within Admin.
inline-formsets
do the trick for a foreign key relationship.
GroupUserInlineFormSet = inlineformset_factory(MyGroup, User, form=PurchaseOrderEditForm, max_num=100, extra=2, can_delete=False)
guformset = GroupUserInlineFormSet (instance=mygroup)
might point you in the right direction. not sure how this can work with a manytomany relationship.
I never found a great way to do this. I ended up writing custom forms that manage creating the fields and specifying an appropriate queryset on them.
For the display portion of the question, there is a way to use the SelectFilter (a.k.a. horizontal filter) on regular pages. One page with instructions I found is here, and there was another that was helpful, but I can't seem to re-located it.
I'm considering writing up a more thorough guide to both parts of this process. If anyone is interested please let me know, it'll give me the push to actually get it done.

How to approach creating Related Links generic (like Comments/Tags) in Django

Since I have not found a Related Links app that works with Django 1.0/trunk, I was looking to create my own.
I would like to attach "Related Links" to models in the same generic way that Comments framework or Tags work.
I've looked over the Content Types documentation but can't wrap my head around (nor find much documentation for) how to use Generic inline formsets - which is what I'm pretty sure I have to use, but correct me if I'm wrong.
My specific requirement is to be able to relate these "Related Links" to almost any model, and to have the form available outside of the Admin - I'll have logged in members of a certain role adding these links, in my specific case.
I thought about tearing into the source of the Comments app, but I know that it uses special template tags, etc, and I'm just not sure if that'd be overkill for this task.
Looking for links, extra documentation, and possibly even examples of using the generic inline formsets (in Generic Views), or solving the problem in a different way if I'm approaching it wrong.
EDIT: I've used James Bennett's example of Generic Inlines to construct and successfully use those Related Links in the Admin. So the real question is: How do I use James' Related Links outside of the Admin?
You can use django.contrib.contenttypes.generic.generic_inlineformset_factory for that. It has the same interface as inlineformset_factory (with 2 additional parameters: ct_field and fk_field, they can be used to specify your model's contenttype's related field names instead of inlineformset_factory's fk_name).
Documentation for inlineformset_factory can be found here:
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
Documentation for formsets is also useful.