Unable to update individual items in Django - django

I am trying to update some information in my Django application but I am getting this error "Cannot assign "9": "Reservation.table" must be a "Tables" instance".
I have tried so manual method also but it still same error.
Error: Cannot assign "9": "Reservation.table" must be a "Tables" instance
views.py
#login_required
def UpdateReservation(request, pk):
table_exists = get_object_or_404(Reservation, id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
form = ReservationForm(request.POST, instance=table_exists)
if form.is_valid():
form = ReservationForm(request.POST, instance=table_exists)
if form.is_valid():
form.save()
return redirect('view_reservations')
messages.success(request, "successfully updated table")
context = {"form": form}
return render(request, "dashboard/super/landlord/update_reserve.html", context)
models.py
class Reservation(models.Model):
status_choices = (
("pending", "pending"),
("confirmed", "confirmed")
)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.EmailField()
phone = PhoneNumberField(blank=True)
people = models.IntegerField(default=1)
time = models.TimeField()
date_reserved = models.DateField()
date_booked = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=10, choices=status_choices, default="confirmed")
comment = models.TextField(blank=True)
table = models.ForeignKey(Tables, on_delete=models.CASCADE)
def __str__(self):
return self.first_name
forms.py
class ReservationForm(forms.ModelForm):
time = forms.CharField(
widget=forms.TextInput(attrs={'id': 'timepicker',
'class': 'input-group',
'placeholder': '12:00:AM'}))
date_reserved = forms.DateField(widget=forms.TextInput(
attrs={'placeholder': 'yyyy-mm-dd',
'id': 'datepicker'}), required=True,)
comment = forms.CharField(widget=forms.TextInput(
attrs={'placeholder': 'Leave a message'}), required=True,)
first_name = forms.CharField(widget=forms.TextInput(
attrs={'placeholder': 'Leave a message'}), required=False,)
email = forms.CharField(widget=forms.TextInput(
attrs={'placeholder': 'Your Email Address'}), required=True,)
phone = forms.CharField(widget=forms.TextInput(
attrs={'placeholder': 'Your Telephone number'}), required=True,)
table = forms.IntegerField(widget=forms.TextInput(
attrs={'placeholder': 'Table Number'}), required=True,)
class Meta:
model = Reservation
fields = ['first_name', 'email', 'time', 'comment',
'phone', 'date_reserved', 'people', 'table']
template.html
<div class="panel-body">
<form class="form-horizontal" role="form" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label class="col-md-2 control-label">{{ field.label }}</label>
<div class="col-md-10">
{{ field|attr:'class:form-control'}}
</div>
</div>
{% endfor %}
<div class="form-group">
<div class="col-md-10">
<center><button class="btn btn-primary" type="submit">Update Reservation</button></center>
</div>
</div>
</div>

You can not make use of an IntegerField, since it expects a Table, not an integer for table. You should use a ModelChoiceField and then use a TextInput as widget:
table = forms.ModelChoiceField(
queryset=Table.objects.all()
widget=forms.TextInput(attrs={'placeholder': 'Table Number'}),
required=True
)

In your form remove your table field from the field list above but keep the one in the Meta, its messing with it because the value is in Integer and you have to assign an object.

Related

How to save Django Form and Formset at the same time

I have a page in which I use a form and formset at the same time. The form is for the thesis information and the formset is for the author.
This is the code in my models.py
class thesisDB(Model):
thesis_id = models.AutoField(primary_key=True, blank=True, null=False)
title = models.CharField(max_length=200, blank=True, null=True, unique=True)
published_date = models.DateField(blank=True, null=True)
pdf = models.FileField(upload_to='pdf/', blank=True, null=True ,validators=[FileExtensionValidator(['pdf'])],)
course = models.ForeignKey(ColCourse, default=None, on_delete=models.CASCADE, verbose_name='Course')
tags = TaggableManager()
date_created = models.DateField(auto_now_add=True, blank=True, null=True )
uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None)
published_status = models.CharField(max_length=10, choices= THESIS_DECISION, default='Pending')
abstract = models.TextField(blank=True, null=True)
hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation')
reason = models.TextField(blank=True, null=True)
slug = models.SlugField(max_length = 250, null = True, blank = True)
def save(self, *args, **kwargs):
self.title = self.title.title()
#self.author = self.author.title()
self.slug = slugify(self.title + "-" + self.author + "-" + str(self.published_date))
super().save(*args, **kwargs)
class Meta:
db_table = 'thesis_storage'
initial_validator = RegexValidator('[A-Z]+.', 'Initial must contain period')
class Authors(Model):
thesis = models.ForeignKey(thesisDB, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200, blank=True, null=True)
last_name = models.CharField(max_length=200, blank=True, null=True)
middle_initial = models.CharField(max_length=2, blank=True, null=True, validators=[initial_validator])
This is the code in my forms.py:
class AuthorForm(forms.ModelForm):
class Meta:
model = Authors
exclude = ()
widgets = {
'first_name': forms.TextInput(attrs=
{'placeholder': 'First Name', 'class':'form-control', 'required': 'required'}),
'last_name': forms.TextInput(attrs=
{'placeholder': 'Last Name', 'class':'form-control', 'required': 'required'}),
'middle_initial': forms.TextInput(attrs=
{'placeholder': 'M.I.', 'class':'form-control', 'required': 'required'}),
}
AuthorFormSet = inlineformset_factory(thesisDB, Authors, form=AuthorForm,
fields=['first_name', 'last_name', 'middle_initial'], extra=3, can_delete=False)
class thesisForm(forms.ModelForm):
class Meta:
model = thesisDB
fields = ('title', 'published_date', 'course','tags', 'abstract', 'pdf',)
readonly_fields = ['date_created']
course = forms.ModelChoiceField(queryset=ColCourse.objects.all().order_by('-course_name'))
# abstract = forms.CharField(widget=CKEditorWidget())
# problem = forms.CharField(widget=CKEditorWidget())
widgets = {
'title': forms.TextInput(attrs=
{'placeholder': 'Title', 'class':'form-control', 'required': 'required'}),
'published_date': forms.DateInput(attrs=
{'class':'form-control', 'required': 'required', 'type':'date'}),
'abstract': forms.Textarea(attrs=
{'placeholder': 'Abstract', 'class':'form-control',}),
'course': forms.Select(attrs=
{'placeholder': 'Short Description', 'class':'regDropDown', 'required': 'required'}),
}
def __init__(self, *args, **kwargs):
super(thesisForm, self).__init__(*args, **kwargs)
# Making location required
self.fields['pdf'].required = True
self.fields['abstract'].required = True
self.fields['tags'].required = True
And this is my views.py for submitting the form.
#login_required
#for_students
def submission(request):
formset = AuthorFormSet()
if request.method == "POST":
form = thesisForm(request.POST, request.FILES)
if form.is_valid() and formset.is_valid():
form.instance.uploaded_by = request.user # set the user
post = form.save() # save the form
formset.instance.thesis = form.instance.thesis_id
post = formset.save()
message = "Your project entitled %s has been submitted successfully! We will notify you through email if it is once evaluated" % form.instance.title
messages.success(request, message)
return redirect('/profile/personal_repository/')
else:
form = thesisForm()
formset = AuthorFormSet()
return render(request,'StudentSubmitProject.html',{'form':form, 'formset':formset})
And my template file:
<div class="container-fluid profilecontainer">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-8 right_section">
<h4 class="textmaroon">Submit A Project</h4>
<p>The requirements for submitting a thesis follows:<p>
<ul>
<li>The softcopy of your thesis which is in PDF format.</li>
<li>The pdf file should contain the approval form attesting the thesis has been approved by your department.</li>
<li>The descriptions of thesis such as its Title, Author, Publication Date, Course, and Keywords.</li>
<li>The abstract text of your thesis which should match in the pdf file.</li>
</ul>
<p>Below is the form for submitting a thesis project. Your project would be evaluated first by the Admin Account before it can be available to access in the system, so ensure that the given details are valid to avoid possible rejection.</p>
<hr></hr>
<form method="POST" class="mt-5 form-group profile_form" enctype="multipart/form-data">
{{formset.management_data }}
{% csrf_token %}
<h4 class="textmaroon">Add author</h4>
<p>Enter the author/s of the thesis project</p>
<hr></hr>
<div class="row">
{% for form_s in formset %}
<div class="col-md-5">
{{form_s.first_name | as_crispy_field}}
</div>
<div class="col-md-5">
{{form_s.last_name | as_crispy_field}}
</div>
<div class="col-md-2">
{{form_s.middle_initial | as_crispy_field}}
</div>
{% endfor %}
</div>
<h4 class="textmaroon mt-5">Describe the thesis</h4>
<p>Define the thesis project</p>
<hr></hr>
<div class="row">
<div class="col-md-12">
{{form | crispy}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-danger mt-3 float-end">Submit</button>
<button type="reset" class="btn btn-secondary mt-3 me-2 float-end">Reset</button>
</div>
</div>
</form>
</div>
<div class="col-lg-2"></div>
</div>
</div>
My problem is that the entered data in the form save, but not in the formset as well.
because you didn't add request.POST to your formset, so no data was passed in the formset:
if request.method == "POST":
formset = AuthorFormSet(request.POST) #need request.POST
form = thesisForm(request.POST, request.FILES)
if form.is_valid() and formset.is_valid():
if there is also file in the formset, add request.FILES as second arg

Django datalist not accepting any input as valid

I am trying to use a datalist input field to allow users to enter their own ingredients on Create a Recipe form. Ideally users can select a GlobalIngredient like salt, pepper, chicken, etc. already in the database or create their own. However, regardless of whether I enter a new ingredient or select a pre-existing ingredient, I am getting the following error: "Select a valid choice. That choice is not one of the available choices.". Unsure why I am getting this error?
Visual:
models.py
class Recipe(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
websiteURL = models.CharField(max_length=200, blank=True, null=True)
image = models.ImageField(upload_to='image/', blank=True, null=True)
name = models.CharField(max_length=220) # grilled chicken pasta
description = models.TextField(blank=True, null=True)
notes = models.TextField(blank=True, null=True)
serves = models.CharField(max_length=30, blank=True, null=True)
prepTime = models.CharField(max_length=50, blank=True, null=True)
cookTime = models.CharField(max_length=50, blank=True, null=True)
class Ingredient(models.Model):
name = models.CharField(max_length=220)
def __str__(self):
return self.name
class GlobalIngredient(Ingredient):
pass # pre-populated ingredients e.g. salt, sugar, flour, tomato
class UserCreatedIngredient(Ingredient): # ingredients user adds, e.g. Big Tomatoes
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL)
description = models.TextField(blank=True, null=True)
quantity = models.CharField(max_length=50, blank=True, null=True) # 400
unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc
forms.py
class RecipeIngredientForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RecipeIngredientForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
#self.helper.form_id = 'id-entryform'
#self.helper.form_class = 'form-inline'
self.helper.layout = Layout(
Div(
Div(Field("ingredient", placeholder="Chickpeas - only write the ingredient here"), css_class='col-6 col-lg-4'),
Div(Field("quantity", placeholder="2 x 400"), css_class='col-6 col-md-4'),
Div(Field("unit", placeholder="grams"), css_class='col-5 col-md-4'),
Div(Field("description", placeholder="No added salt tins - All other information, chopped, diced, whisked!", rows='3'), css_class='col-12'),
css_class="row",
),
)
class Meta:
model = RecipeIngredient
fields = ['ingredient', 'quantity', 'unit', 'description']
labels = {
'ingredient': "Ingredient",
"quantity:": "Ingredient Quantity",
"unit": "Unit",
"description:": "Ingredient Description"}
widgets={'ingredient': forms.TextInput(attrs={
'class': 'dropdown',
'list' : 'master_ingredients',
'placeholder': "Chickpeas - only write the ingredient here"
})}
views.py
#login_required
def recipe_create_view(request):
ingredient_list = Ingredient.objects.all()
form = RecipeForm(request.POST or None)
# Formset = modelformset_factory(Model, form=ModelForm, extra=0)
RecipeIngredientFormset = formset_factory(RecipeIngredientForm)
formset = RecipeIngredientFormset(request.POST or None)
RecipeInstructionsFormset = formset_factory(RecipeInstructionForm, extra=0)
instructionFormset = RecipeInstructionsFormset(request.POST or None, initial=[{'stepName': "Step 1"}], prefix="instruction")
context = {
"form": form,
"formset": formset,
"instructionFormset": instructionFormset,
"ingredient_list": ingredient_list
}
if request.method == "POST":
print(request.POST)
if form.is_valid() and formset.is_valid() and instructionFormset.is_valid():
parent = form.save(commit=False)
parent.user = request.user
parent.save()
# formset.save()
#recipe ingredients
for form in formset:
child = form.save(commit=False)
print(child.ingredient)
globalIngredient = Ingredient.objects.filter(name=child.ingredient.lower()) # not truly global as this will return user ingredients too
if (globalIngredient):
pass
else:
newIngredient = UserCreatedIngredient(user=request.user, name=child.ingredient.lower())
newIngredient.save()
if form.instance.ingredient.strip() == '':
pass
else:
child.recipe = parent
child.save()
# recipe instructions
for instructionForm in instructionFormset:
instructionChild = instructionForm.save(commit=False)
if instructionForm.instance.instructions.strip() == '':
pass
else:
instructionChild.recipe = parent
instructionChild.save()
context['message'] = 'Data saved.'
return redirect(parent.get_absolute_url())
else:
form = RecipeForm(request.POST or None)
formset = RecipeIngredientFormset()
instructionFormset = RecipeInstructionsFormset()
return render(request, "recipes/create.html", context)
create.html
<!--RECIPE INGREDIENTS-->
{% if formset %}
<h3 class="mt-4 mb-3">Ingredients</h3>
{{ formset.management_form|crispy }}
<div id='ingredient-form-list'>
{% for ingredient in formset %}
<div class='ingredient-form'>
{% crispy ingredient %}
</div>
{% endfor %}
<datalist id="master_ingredients">
{% for k in ingredient_list %}
<option value="{{k.name|title}}"></option>
{% endfor %}
</datalist>
</div>
<div id='empty-form' class='hidden'>
<div class="row mt-4">
<div class="col-6">{{ formset.empty_form.ingredient|as_crispy_field }}</div>
<div class="col-6">{{ formset.empty_form.quantity|as_crispy_field }}</div>
<div class="col-6">{{ formset.empty_form.unit|as_crispy_field }}</div>
<div id="ingredientIdForChanging" style="display: none;"><div class="col-12">{{ formset.empty_form.description|as_crispy_field }}</div><button type="button"
class="btn btn-outline-danger my-2" onclick="myFunction('showDescription')"><i class="bi bi-dash-circle"></i> Hide
Description</button></div><button type="button"
class="btn btn-outline-primary col-5 col-md-3 col-lg-3 col-xl-3 m-2" id="ingredientIdForChanging1"
onclick="myFunction('showDescription')"><i class="bi bi-plus-circle"></i> Add a
Description Field</button>
</div>
</div>
<button class="btn btn-success my-2" id='add-more' type='button'>Add more ingredients</button>
{% endif %}

Many to many fields in widget form

I have problem with display many to many field in form widget.
Category is not display in template.
Title is ok (is display) but category isn't - category is empty.
What can I do to display many to many fields in my template form with multiplechoice checkboxes?
Why I cant display article categories in widget form?
MODELS.py
article model:
class Article(Created, HitCountMixin):
title = models.CharField(max_length=120)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
category = models.ManyToManyField(ArticleCategory, related_name='articles')
category model:
class ArticleCategory(Created):
category_name = models.CharField(max_length=128)
slug = models.SlugField(null=False, unique=False)
VIEWS:
class UpdateArticleView(LoginRequiredMixin, UpdateView):
template_name = 'news/update_article.html'
form_class = EditArticleForm
model = Article
def get_success_url(self):
pk = self.kwargs["pk"]
slug = self.kwargs['slug']
return reverse_lazy("news:article_detail", kwargs={'pk': pk, 'slug': slug})
FORMS.py
class AddArticleForm(forms.ModelForm):
title = forms.CharField(
label="Tytuł",
max_length=120,
help_text="Tytuł newsa",
widget=forms.TextInput(attrs={"class": "form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded"}),
required=True,
)
category = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
)
And in my HTML TEMPLATE:
<form method="post" enctype='multipart/form-data'>
{% csrf_token %}
{{ form.media }}
{# {% crispy form %}#}
{{ form|crispy }}
<button type="submit" class="btn btn-outline-primary">EDYTUJ NEWS</button>
</form>
Your form_class in your view is a EditArticleForm, so you should be careful to use the correct form.
The form field for a ManyToManyField is normally a ModelMultipleChoiceField [Django-doc], but it is not necessary to specify the form field anyway. You can make use of the widgets option:
class EditArticleForm(forms.ModelForm):
title = forms.CharField(
label='Tytuł',
max_length=120,
help_text='Tytuł newsa',
widget=forms.TextInput(
attrs={'class': 'form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded'}
),
required=True,
)
class Meta:
model = Article
widgets = {
'category': forms.CheckboxSelectMultiple
}
you can customize the label with:
class EditArticleForm(forms.ModelForm):
title = forms.CharField(
label='Tytuł',
max_length=120,
help_text='Tytuł newsa',
widget=forms.TextInput(
attrs={'class': 'form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded'}
),
required=True,
)
class Meta:
model = Article
widgets = {
'category': forms.CheckboxSelectMultiple
}
labels = {
'category': 'label of category'
}

Django form : Doesn't display any form errors

I'm getting an issue with my Django form validation. I would like to display form errors and make all fields required. I don't know why my fields can accept blank while blank is not defined in my model file.
This is my model :
class Customer(models.Model):
email = models.CharField(max_length=150, verbose_name=_('e-mail'), null=False)
first_name = models.CharField(max_length=70, verbose_name=_('first name'), null=False)
last_name = models.CharField(max_length=70, verbose_name=_('last name'), null=False)
country = models.ForeignKey(Country, verbose_name=_('country'))
institution = models.CharField(max_length=255, verbose_name=_('institution'), null=True)
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('customer')
verbose_name_plural = _('customer')
def __str__(self):
return f"{self.email}"
This is my form :
class CustomerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CustomerForm, self).__init__(*args, **kwargs)
self.fields['country'].empty_label = _('Select a country')
self.fields['country'].queryset = self.fields['country'].queryset.order_by(
'name')
for key in self.fields:
self.fields[key].required = True
class Meta:
model = Customer
fields = ['email', 'first_name', 'last_name', 'country', 'institution']
widgets = {
'email': forms.TextInput(attrs={'placeholder': _('name#example.com')}),
'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}),
'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}),
'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}),
}
You can find here my view with Django CBV :
class HomeView(CreateView):
""" Render the home page """
template_name = 'app/index.html'
form_class = CustomerForm
def get_context_data(self, **kwargs):
kwargs['document_list'] = Document.objects.all().order_by('publication__category__name')
return super(HomeView, self).get_context_data(**kwargs)
def post(self, request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseRedirect(self.get_success_url())
form = self.form_class(request.POST)
email = request.POST['email']
country_id = request.POST['country']
country = Country.objects.get(id=country_id)
for checkbox in request.POST.getlist('DocumentChoice'):
document = Document.objects.get(id=checkbox)
token = self.gen_token(email, document.edqm_id)
Download.objects.create(email=email, country=country, pub_id=checkbox, token=token,
expiration_date=now + timedelta(minutes=10))
if not form.is_valid():
print('form invalid')
continue
return HttpResponseRedirect(self.get_success_url())
And finally my template :
{% extends "publication/base_backend.html" %}
{% load staticfiles %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block main %}
<form method="post" id="customerform" novalidate>
{% csrf_token %}
<h3>{% trans 'Your information' %}</h3>
<hr>
<div class="col-sm-12 col-md-12 col-lg-12">
{{ form.email|as_crispy_field:"bootstrap" }}
</div>
<br />
<br />
<br />
<br />
<div class="alert alert-info col-sm-12 col-md-12 col-lg-12" role="alert">
<small>{% trans "The fields below are optional if you have already requested a publication:" %}</small>
</div>
<div class="col-sm-5 col-md-5 col-lg-5">
{{ form.first_name|as_crispy_field:"bootstrap" }}<br>
{{ form.country|as_crispy_field:"bootstrap" }}
</div>
<div class="col-sm-5 col-md-5 col-lg-5 col-sm-offset-2 col-md-offset-2 col-lg-offset-2">
{{ form.last_name|as_crispy_field:"bootstrap" }}<br>
{{ form.institution|as_crispy_field:"bootstrap" }}
</div>
<div class="col-md-12">
<br />
<br />
</div>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/>
{% trans 'Cancel' %}
</form>
Issues :
According to required fields, I don't know why my form doesn't display missing values errors when I want to submit it.
I have to display fields as shown in my template because I have to make bootstrap design.
In order to display form errors, I have to write {{form.email.errors}} for example but nothing appears.
Thank you by advance

How to have additional field besides the fields in the model in ModelForm

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'})
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']
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>