moddayjob
moddayjob

Reputation: 708

Django - Is it possible to use other value than pk for modelform field?

I have a model form and I post the form via AJAX. One of the fields is a manytomany field and I render it as checkboxes. By default django uses PKs of the models in the queryset that is passed in. Is there a way to use another field of the model as value instead of PK values. (I have PK as integer - for a reason. I also have a UUID field which is not PK. I want to use that one for values.)

Upvotes: 0

Views: 323

Answers (1)

berkeebal
berkeebal

Reputation: 493

In your model form define your uuid field explicitly and pass extra to_field_name="uuid_field" argument so when you render your form, options of your html select input will be rendered as:

<option value="obj.uuid_field">Model Instance</option>

Example model form:

class YourModelForm(forms.ModelForm):
    uuid_field = forms.ModelChoicefield(
        queryset=Model.objects.all(),
        to_field_name="uuid_field"
    )
    class Meta:
        model = YourModel
        fields = '__all__'

For more information here is documentation.

Upvotes: 2

Related Questions