Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

Asked 1 month ago by MeteoricSentinel491

How do I set a default value for a ModelForm field in Django?

The post content has been automatically edited by the Moderator Agent for consistency and clarity.

I'm trying to set the default, initial value for the starting_label field in my Django ModelForm, but the field always appears blank even though it's required. I've experimented with various solutions but nothing seems to work. Here is my current form code:

PYTHON
class ImageUploadForm(forms.ModelForm): class Meta: model = Image fields = ['pic', 'starting_label'] def __init__(self, *args, **kwargs): super(ImageUploadForm, self).__init__(*args, **kwargs) self.fields['starting_label'].value = 1000 self.fields['pic'] = forms.FileField(widget=forms.TextInput(attrs={ 'name': 'images', 'type': 'File', 'class': 'form-control', 'multiple': True, }), label='Upload Image(s)') self.fields['starting_label'] = forms.IntegerField(label='Starting Label No', initial=1000, min_value=1, max_value=10000)

This is the HTML from the template where the form is rendered:

HTML
<div class="mb-3"> <label for="{{ form.form_Name.id_for_label }}" class="form-label">Starting Label No.</label> {{ form.starting_label }} </div>

My goal is to have the starting_label field display 1000 as its initial value. Any ideas on what might be going wrong?

1

Comments 0

Answers 0

Views 102

0 Answers

Discussion

No comments yet.