In my Django forms I have 5 fields but I will take 4 of them from the html template. The 5. one will be filled in the views. When I try to do like this it says form is not valid. How can I fill the data in views?
forms.py
class ProductForm(forms.ModelForm):
class Meta:
model = ProductModel
fields = ('category','brand','series','model','asin')
productform.html
<form id="firstform" action="{% url 'productpage' %}" method="POST">
{% csrf_token %}
<input type="text" id="category" name="category" placeholder="Category">
<input type="text" id="brand" name="brand" placeholder="Brand">
<input type="text" id="series" name="series" placeholder="Series">
<input type="text" id="model" name="model" placeholder="Model">
<input type="submit" id="save-button" name="save-button" value="Save" >
</form>
views.py
def productpage(request):
if request.POST.get('save-button'):
form = ProductForm()
if request.method == 'POST':
form = ProductForm(data=request.POST)
if form.is_valid():
form.cleaned_data["asin"] = "B324235252"
form.save()
HttpResponse("SAVED")
else:
print("iiii")
HttpResponse("Form is not valid")
else:
form = ProductForm()
return render(request,"first_app/productform.html")
CodePudding user response:
Exclude the field from the form:
class ProductForm(forms.ModelForm):
class Meta:
model = ProductModel
fields = ('category','brand','series','model') #