Creating Model Relationships Via Forms - django

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/

Related

how to correctly assign the through attribute in django?

I was just looking the documentation to be able to change the intermediate table but when I implement it, I get into trouble:
https://docs.djangoproject.com/en/2.0/topics/db/models/#extra-fields-on-many-to-many-relationships
The problem as such is that, although I can migrate the database and run the application, when I enter the administrator I do not visualize correctly the relationship of my models through the trough attribute (especially a field of my model called Tested).
Why does this happen and how can it be corrected?
This is by design. Django cannot automatically generate the widget for ManyToMany relations that use a through table because of the extra data needed (tested in your case). From Django docs:
When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.
However, we still want to be able to edit that information inline. Fortunately, this is easy to do with inline admin models.
Your best bet is to create an inline admin model as explained in the docs.

How can I use model like a custom field

Recently I've been developing a Django website, which includes the owner being able to add content with descriptions etc.
The problem I'm having is: How can I make the fields support multiple languages? (3 in this case)
The approach I tried was: Creating a model with 3 text fields, have my content model take that model as a foreign key. This sort of works, but now I would have to create all the descriptions first, separately, before creating the actual object it is being used by. This is, in my opinion, a bad idea.
What I would like to be able to do, is to have 3 text fields in the model which is actually using those 3 text fields' admin page, but without actually having 3 text fields in that model.
Using inlines would work, but I'd have to make my multilanguage textfield model have a foreign key to my content model, instead of the other way. This would mean the multilanguage model works for only other model type.
So, to clear the question up:
How can I have a TextField and a CharField support multiple languages?
How can I show the ForeignKey's target model's creation widget in it's owner's admin page?
How can I use inlines, without locking the inline to just one model type?
How can I make a model act like a field?
How can I write a custom TextField?
Answering any of those will be enough for me to solve my problem.
Thanks.
There is too many questions and the docs is at your reach... I'll just answer the easiest one you should have search for by yourself.
How can I have a TextField and a CharField support multiple languages?
You should have a look to i18n here
How can I write a custom TextField?
Have a look to custom Fields

fields automatically added by django

By default, Django automatically gives each model an id field.
Are there any additional fields django's ORM adds automatically? Perhaps in specific cases?
There are only 2 other situations I can think of where fields are automatically created. One is when sub-classing another model. The sub-class will inherit the parent's fields, see here. The other is a Many-to-Many relationship. For a M2M relationship not only will a field get created but an entire intermediate table. Again, the relevant docs
Also, you can avoid having Django create the id field if you specify primary=True for the field you want to use as the primary key. See here
There are some other model/DB naming conventions as well. For example, the actual database table names will be prefixed with the Django app name that contains them plus an underscore. For example, a model named Author in an app named library will get called library_author. I'm sure there are other examples as well, so this is not an exhaustive list.

Can I make Django admin reflect a hierarchy of models?

Assume a Django application with a few models connected by one-to-many relationships:
class Blog(models.Model):
...
class Post(models.Model):
blog = models.ForeignKey(Blog)
...
class Comment(models.Model):
post = models.ForeignKey(Post)
...
Conceptually, they form a hierarchy, a tree-like structure. I want the Django admin to reflect that. In particular:
in a changelist of posts, every post should have a link to the changelist of corresponding comments;
similarly, a post’s edit page should link to the changelist of comments from the top-right buttons area;
when I open that list of related comments, it needs to reflect the relationship in the breadcrumbs (something like: Posts › “Hello world” › Comments) and, ideally, also in the URL (post/123/comment/).
This should of course also apply to the other levels of the hierarchy.
Number 1 is pretty easy with a custom list_display entry and using the ?post__id= query to the comments changelist. But this is little more than a hack. Generally Django assumes my three models to be independent, top-level entities.
Is there a straightforward way to accomplish this? I guess I could override a bunch of templates and AdminModel methods, but perhaps there is a better solution for what seems like a common situation?
Are you sure you are not just looking at Django Admin Inline Models ?
There is no way that an automated admin will pick up your relationships, because in an RDBS there can be any number of foreign keys / one to one / many to many relations, and Django does not have a customized hierarchical behavior built in.
You can indeed edit the breadcrumb customizing an admin template if you want.
For relations you might also be interested into django MPTT that allows to make hierarchical model instances. Also see this question: Creating efficient database queries for hierarchical models (django) in that respect.
How is this a common situation? Consider the fact a model can have a virtually unlimited number of foreign key relationships, let alone visa versa. How would the admin 'know' how to represent this data the way a user requires without customizing things?
One would suggest you are used to work with content management systems rather than webframeworks (no pun intended). It's important to notice Django isn't a cms, but a webframework you can built on top of as you see fit. In a nutshell: 'Django is rather clueless and unaware of contextual requirements'.
Although the admin is quite a beast out-of-the-box, it can be hard to customize. There have been quite some discussions whether it should even be part of core. I can only suggest, if customizing things tends to get hacky, you should probably write your own 'admin', it's not that hard.

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.