[Answered ]-Django Form initial Value For Foreignkey Field

1👍

Passing values in initial for excluded fields does not do anything. Instead what you can do is modify the instance wrapped by the form before saving the it:

def create_source(request, dataset_id):

    user = request.user
    dataset = Dataset.objects.get(id=dataset_id)

    form = SourceForm() # No initial

    if request.method == "POST":
        form = SourceForm(request.POST) # this is a submitted form `request.POST or None` makes no sense use only `request.POST`
        if form.is_valid():
            form.instance.dataset = dataset
            source = form.save()
            return redirect("source", dataset_id=dataset_id, source_id=source.id)

    context = {"form": form}
    return render(request, "sources/source_form.html", context)

Leave a comment