Reputation: 149
I have a model named Customer and modelForm named Customer, but in my form i need more fields than the fields in Model. For example i want a confPass field in my ModelForm. Code for Model:
class Customer(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=100, unique=True)
mobile_no = models.CharField(unique=True, validators=[validate_mobile], max_length=10)
state = models.CharField(choices=STATES, max_length=2)
city = models.CharField(max_length=20)
password = models.CharField(max_length=256)
def __str__(self):
return self.email
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = ['name', 'email', 'mobile_no', 'state', 'city', 'password']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'placeholder': 'Enter Name', 'class': 'form-control'})
self.fields['email'].widget.attrs.update({'placeholder': 'Enter Email', 'class': 'form-control'})
self.fields['mobile_no'].widget.attrs.update({'placeholder': 'Enter Mobile Number ', 'class': 'form-control'})
self.fields['state'].widget.attrs.update({'class': 'form-control'})
self.fields['city'].widget.attrs.update({'placeholder': 'Enter City', 'class': 'form-control'})
self.fields['password'].widget.attrs.update({'class': 'form-control'})
Upvotes: 1
Views: 112
Reputation: 19
I had to do this for a GenericRelation field, 'task'. I wanted to add a field that was in the model but wouldn't display in the ModelForm. I was able to update the field only using the shell. I added an tag after the form and then processed the response in the def form_valid() function. My problem was that I have a task_app that I use for different models, so I needed a GenericRelation.
views.py
class ProjectModelUpdateView(UpdateView):
model = ProjectModel
# fields = '__all__'
form_class = ProjectModelForm
success_url = '/projects_app/'
def form_valid(self, form):
form.instance.updated_by = self.request.user
project = ProjectModel.objects.get(id=form.instance.id)
project.task.create(created_by=self.request.user, task=self.request.POST['task'])
return super().form_valid(form)
HTML
<form method="post">
{% csrf_token %}
{% for field in form %}
<label class="control-label" for="{{ field.auto_id }}">{{ field.label }}</label>
<div class="col-sm-5 border rounded form-outline">
{{ field }}
</div>
{% endfor %}
<label class="control-label" for="id_task">Task</label>
<div class="col-sm-5 border rounded form-outline">
<input type="text" name="task" maxlength="64" class="form-control" id="id_task">
</div>
<br>
<input type="submit" value="Save">
</form>
Upvotes: 0
Reputation: 2675
Just add the field to your CustomerForm
class and include it in fields
list:
class CustomerForm(ModelForm):
confPass = forms.CharField()
class Meta:
model = Customer
fields = ['name', 'email', 'mobile_no', 'state', 'city', 'password', 'confPass']
Upvotes: 1