Django ModelForm with Select Widget - Use object.uid as default option value instead of object.id

故事扮演 提交于 2019-12-22 08:25:18

问题


I have a form inheriting from ModelForm as such:

class ChildModel(ModelForm):
      class Meta:
          model = Documents
          fields = ('secretdocs')
          widgets = {
              'secretdocs': Select(attrs={'class': 'select'}),
          }

The model "secretdocs" has a uid. But when it prints out the select and option, the option values appear as such:

<select class="select" id="id_secretdocs" name="secretdocs">
    <option value="1">My Secret Doc</option>
</select>

But I want it to instead have the uid of the option:

<select class="select" id="id_secretdocs" name="secretdocs">
    <option value="cd2feb4a-58cc-49e7-b46e-e2702c8558fd">My Secret Doc</option>
</select>

I've so far tried to use BaseForm's data object and overwriting Select's value_from_datadict method but I'm pretty sure that wasn't the right approach. Does anyone know how I can do this?

Thanks in advance.


回答1:


You can do something like this:

class ChildModel(ModelForm):

  secretdocs = forms.ChoiceField(choices=[(doc.uid, doc.name) for doc in Document.objects.all()])
  class Meta:
      model = Documents
      fields = ('secretdocs', )
      widgets = {
          'secretdocs': Select(attrs={'class': 'select'}),
      }



回答2:


I think part of the "right" way to do this is to ensure that the UUID field is set as the primary key of the model in question and that there is no autonumber ID field.

For example:

class Document(models.Model):
    uuid = models.YourCustomUUIDField(primary_key=True,.....)
    other_field = models.CharField(.....)
    ....

If you do it this way, I think Django will pick up the UUID field as a primary key and use it in all places. If, however, you do wish to keep the built-in autoincrementing primary key field and use the UUID only here, you could do something similar to what karthikr suggests in those forms where the UUID field is required.



来源:https://stackoverflow.com/questions/15960930/django-modelform-with-select-widget-use-object-uid-as-default-option-value-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!