[Django]-Django CharFIeld with unique=True update error "Instance with this Name already exists"


The reason that this will fail is because the ModelForm thinks you are creating a new record, and thus it will check if an object with the given name already exists, and if so, it of course finds out the name already exists, hence the form is not valid.

You can pass the instance to the form. In that case the form will exclude that item from the unique check:

def course_update(request, pk):
    course = Course.objects.get(pk=pk)
    course_queryset = Course.objects.filter(pk=pk)
    if request.method == 'POST':
        form = CourseCreateForm(request.POST, instance=course)
        if form.is_valid():
            name = name_form.cleaned_data['name']
            other_field = course_form.cleaned_data['other_field']
            course_queryset.update(name=name, other_field=other_field)
            return HttpResponseRedirect('../')
        form = CourseCreateForm(instance=course)
        context = {
            'name_form': name_form,
            'course_form': course_form,
        return render(request, 'base/course_update.html', context)

Leave a comment