Django: dropdown value not in list

I am trying to enter a value into a dropdown that is NOT in the list using Django

. The default is read from the database.
But the trick is that the user can see the value, but not change it.

Is there a way to do this using Django

?
Django

will not let me display something in the dropdown that is not defined in models.py

, so the object remains empty.

Any ideas? Maybe a walk?

thank

code:

aList = (('OK', 'OK'), ('Not', 'Not'))

class sampleModel(models.Model):
  name = models.CharField(max_length=32, blank=True)
  res = models.CharField(max_length=10, blank=True, choices=aList)

      

An OK * and Not * record comes from another database. I need to display this OK * / Not * dropdown, but so that the user cannot use it, but can still change to normal OK / Not.

+3


source to share


1 answer


One simple option might be to add an empty selection to your selections, for example:

aList = (
    ('', 'OK/Not') 
    ('OK', 'OK'), 
    ('Not', 'Not')
)

      

and make the field res

required so that you cannot pass a null value, so if the user selects an empty choice, the form returns an error until they choose one of the valid options

You must change your field:

res = models.CharField(max_length=10, blank=True, choices=aList)

      

for

res = models.CharField(max_length=10, choices=aList)

      

The only change that was made was to remove blank = True so that the field is requried.

This all assumes that you have a Django ModelForm that you created based on your model.



Another option, to avoid modifying the model, would be to control the selection in the view. If you have a choice in HTML with 3 choices:

<select name="mySelect" id="id_mySelect">
  <option value="" selected="selected">Please select value</option>
  <option value="value1">Ok</option>
  <option value="value2">Not</option>
</select>

      

So when you receive a POST in your view, you can do something like:

error = False
error_text = ''
# Manually get the value of the select in your view
myselect = request.POST.get('mySelect', None)

# If the value of the select is '' return an error to the template
if not myselect:
   error = True
   error_text = 'You have to select an option'
   return ('yourtemplate.html', {'error':error, 'error_text': error_text}, context_instance=RequestContext(request) )

      

and you only need to manage this custom error that you return to the template

You do have many opportunities to do what you are trying to do, but to help us help you, we need more information about your project, usually some of the pieces of code that you have right now, and how you manage it.

Parameters required for execution:

  • Make the field required and use ModelForm
  • Create a custom form and set up field validation (as @dukeboy suggested)
  • Make a selection of pure HTML and manipulate it in the view
  • ...
+1


source







All Articles