Creating a ModelForm where my primary key field generates a select box
I am not sure if my language clear enough but basically I have this form:
class Paper(models.Model):
number = models.CharField(max_length=12,primary_key=True)
project = models.ForeignKey(Project)
class SomeForm(forms.ModelForm):
class Meta:
model = Paper
fields = ('project', 'number开发者_如何学运维')
and django creates a textfield for me. What I want is a select box with the existing primary keys.
Thanks.
I don't think you want a modelform - that's for creating and updating model instances. It sounds like you just want a form to select IDs. Use a normal form, but with a ModelChoiceField
.
class SomeForm(forms.Form):
ids = forms.ModelChoiceField(queryset=Paper.objects.all())
You'll need to give the Paper
model a __unicode__
method that returns self.number
.
精彩评论