Tuesday, November 29, 2016

Add form fields/values at ModelForm level or at CBV level.


I have a model Product which a Foreign Key to a Company model. The Company Model has a OneToOne Relationship to user.

When a user submits a form to add product I need to associate the product with the company of the user (the user doesn't need to add manually the company in the form)

There are 2 methods:

1) adding a new user field in the ModelForm  __init__ method:

self.company = kwargs.pop('company')

and then at the CBV level using get_form_kwargs

kwargs['company'] = self.get_company()


2) or directlly at the CBV level using form_valid:

self.instance.company = self.get_company()



Which one is better (besides more lines for the first one) as implementation ? What is the difference ?


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/90e88059-7405-484e-987a-ead89954fe9e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment