so new to python & django moving along nice on a project but cant find any simple answers to the above question:
Models are like this
class Projects(models.Model):
project_name = models.CharField(max_length=200)
project_description = models.TextField(blank=True)
active = models.BooleanField()
def __unicode__(self):
return self.project_name
I have other models that refer to the above as a ForignKey like
class Estimates(models.Model):
client = models.ForeignKey(Clients)
estimate_summary = models.CharField(max_length=200,blank=True)
project = models.ForeignKey(Projects,default=-1,blank=True)
I know I can set blank=False to ensure I am getting a valid choice, however I want to allow them the option of not assigning a project to the estimate, in which case I would store a default integer -1 or something.
Problem however is I cant figure how to get the form to use an Integer as its default value instead of ” ” <- (empty string)
<option selected="selected" value="">---------</option>
<option value="1">Sample Project</option>
All the questions and answers I have seen revolve around changing the --------- to some other text or forcing you to remove the blank option all together. I just want
<option selected="selected" value="-1">---------</option>
So my form will validate
When finished writing the question I wondered if I could insert an option myself and use empty_label=None when adding to the form
field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
First of all, you don’t want to use an Integer of -1 as default. For ForeignKeys you usually use null=True in combination with blank=True if you don’t require it (Don’t forget to drop and recreate the table or use south to migrate it — also remove default then since None is a valid option with null=True and as such no default is required). This way if you don’t assign a project you will get NULL in the database which is also what the Admin supports — -1 will break more than it solves.
As soon as you use null=True, blank=True ModelChoiceField will automatically work as you want.