1π
Ok, so after a lot of "when in doubt cout", I noticed that model forms only check constraints that include all the fields that the form includes. In my case the model included
'location',
'department',
'catagory',
'reason',
but the constraint included company
. I did not add company here as it is not something the user sets in the form, but it is a hidden field. Point is that the constraint did not trigger as the constraint includes company. Adding company to the fields list in the model form resolved my problem.
0π
The issue is with the form.save(commit=False)
line, which does not include all the fields necessary to satisfy the unique constraints specified in the modelβs Meta
class. When you call form.save(commit=False)
, you are creating a new instance of the DataMapping
model that has not yet been saved to the database. Then you are assigning the company field to the current company, but you are not assigning values to the other fields that are part of the unique constraint.
Try to add those fields before calling form.save()
like so:
def data_mapping_new(request):
company = get_current_logged_in_company(request)
if request.method == "POST":
form = DataMapForm(request.POST or None)
if form.is_valid():
data_mapping = form.save(commit=False)
data_mapping.company = company
data_mapping.location = form.cleaned_data['location']
data_mapping.department = form.cleaned_data['department']
data_mapping.catagory = form.cleaned_data['catagory']
data_mapping.reason = form.cleaned_data['reason']
data_mapping.save()
# ...
The above solution should work but additionally Iβd recommend you to see Using request.POST or None
antipattern made by Sir Willem Van Onsem.
- [Answered ]-Django dynamic form thinks it has been posted
- [Answered ]-Reload the table without refreshing the page in Django
- [Answered ]-Django β Differences in System date and Django Template Tag date