I’ve built a little app with models Page and Mark.
Mark also has a ModelForm class MarkForm, which I’ve told to display all of its attributes as widgets, except ForeignKey, which is editable=False. There’s a one-to-many relationship between Page and Mark – one Page, many Marks.
When I try to submit the MarkForm, however, it nags that the ForeignKey field cannot be blank – is there a way to tell the form automatically (on the server side), that , so that there won’t be a form output in the html (I don’t want users to be able to fiddle and add marks to other Pages).
If I’m missing something, please let me know, maybe I’ve done something wrong in my models or views. Here’s some code:
class Mark(models.Model):
page = models.ForeignKey(Page, editable=False)
x = models.IntegerField()
y = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
body = models.CharField(max_length=200)
class MarkForm(forms.ModelForm):
class Meta:
model = Mark
widgets = {
'x': HiddenInput(),
'y': HiddenInput(),
'width': HiddenInput(),
'height': HiddenInput(),
'body': HiddenInput(),
}
To exclude a field, you can do it in the ModelForm’s Meta class.
To pre-set a field value, you could do in the view, e.g.: