Sunday, October 23, 2016

Silently continuing past an exception: is this proper? how else can I do this?

I've got my models setup in Django where a Document is a model that can be related to a Transaction.
Now I'd like to make a DocumentForm with a dropdown of Transactions owned by the current Client, so that a client can say that this Document is related to this Transaction.

So I wrote some code that looks like this:
class DocumentForm(forms.ModelForm):
    path
= forms.FileField(label='Choose a file')
    description
= forms.CharField(label='What is it?')
    related_to
= forms.ModelChoiceField(queryset=Transaction.objects.none())

   
class Meta:
        model
= Document
        fields
= ['description', 'path', 'related_to']

   
def __init__(self, *args, **kwargs):
       
super(DocumentForm, self).__init__(*args, **kwargs)
       
self.fields["related_to"].queryset = Transaction.objects.filter(client=self.data.client)

So now I can do:
d = Document()
DocumentForm(d)

and the related_to field in this DocumentForm will automatically be populated by Transactions owned by the current client.

The problem is, when Document() isn't yet saved to the db, it isn't associated with a client. So DocumentForm's self.data.client will throw an exception, and I can't test for it with if.

So I'm thinking of just using try/except and doing nothing on except.

Is there a better way to do this? I heard that you shouldn't use exceptions for control flow, but here it looks like I am.

--
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/6cce68bc-03be-4a8c-a58b-ec9b0bf43153%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment