Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 981
limasxgoesto0 Avatar asked Apr 12 '13 00:04

limasxgoesto0


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What a widget is Django how can you use it HTML input elements?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .

How do you make a model field required in Django?

In order to make the summary field required, we need to create a custom form for the Post model. I am making them on the same file you can do this on a separate forms.py file as well. As intended we create the custom model form and in the __init__ method we made the summary field required.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


1 Answers

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'}),
      }
like image 185
karthikr Avatar answered Sep 21 '22 01:09

karthikr