I'm a Floridian web engineer who planted his roots in Paris. Some of my favorite past-times are analyzing and optimizing development processes, building solid APIs, mentoring junior devs, and long walks on the beach.
I just added a bit of code for creating an object with an association in Django. I saw quite a few tutorials that mix the setting of associated data directly into the view. In general, this is not recommended as django views should be for handling the passing of of data that will be rendered and the likes. Form processing should be handled in the Form classes. Here is an example of a not so great solution:
def some_view(request): obj_form = ObjectForm.new(request.POST) other_obj = OtherObj.objects.find(pk=request.POST['other_obj_id']) obj = obj_form.save() obj.other_obj = other_obj obj.save() return render(request, 'object.html')
Django supports the setting of associations with ModelChoiceField. However there is a caveat in that you must specify a queryset. I wanted the associated object other_obj to be able to be any row from the table that represents OtherObj, but this table will grow with time. For my needs I don't need to limit my associations to the queryset and what's more, as the table grows, the queryset will become less manageable.
Therefore, I modified the form class as follows:
class ObjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ObjectForm, self).__init__(*args, **kwargs) self.other_obj_id = self.data['other_obj_id'] def save(self, *args, **kwargs): self.instance.other_obj_id = self.other_obj_id return super(ObjectForm, self).save(*args, **kwargs)
In this way, I can keep everything relative to the manipulation of the Object class within ObjectForm instead of having it spread between the view and form classes.