Siphiwe Gwebu
Siphiwe Gwebu

Reputation: 609

Django: How to achieve logical mapping between form fields and model fields?

If I have:

class MyForm(ModelForm):
    class Meta:
        model = MyModel
    generic_field = CharField()

and

class MyModel(models.Model):

    field_x       = models.CharField(unique=True, null=True, blank=True)
    field_y       = models.CharField(unique=True, null=True, blank=True)
    field_z       = models.CharField(unique=True, null=True, blank=True)

and in a view:

if request.method == 'POST':
    my_form = MyForm(
     {'field_x': generate_field_x(request.POST['generic_field']), 'field_y': generate_field_y(request.POST['generic_field']),
     'field_z': generate_field_z(request.POST['generic_field']),
     },
     request.POST)

This works well to marshal generic_field onto the correct model field. The problem occurs when there is/are validation errors. How do I marshal model validation errors (field_x/y/z) back onto generic_field? The goal is to get the user to seamlessly interact with generic_field, validation and all.

Disclaimer: 1. I'm new to Django, pls excuse any clumsiness in my post. 2. I did dig around and hit brick walls everywhere, possibly because I don't know how to phrase this properly. Please help/point me in the right direction.

Upvotes: 0

Views: 1063

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799062

Your question is a little vague, but it sounds like you want to create a custom field that maps to multiple concrete fields in the model, but has a single presence in a form.

Upvotes: 1

Related Questions