Django initial value for MultiChoice Field ignored for ModelForm

250 views Asked by At

this is my first post here and I am very new to Django but I just can't seem to find a solution for this problem... I've searched stackoverflow and google but nothing seems to work for me...

I have a wine-app and want to be able to add and remove wines from the user's stock. In the list of wines the user can choose a wine to add and the ID of this wine is passed in the POST data. Since the data is getting lost after the first time the view is rendered I saved the ID in a cookie, which is working, but the problem is when I work with ModelForm de user has to select the foreign key for the user and for the wine, which is bad, so I tried to make it hidden and set the Fk_user and Fk_wine after the user choose the number of bottles to be added but before validation. Here's the problem after google everyone suggested I should use the "initial" and pass that to the form, but this is clearly not working because if I make the fields visible in the form I can see that it is not preselected...

viewy.py:

def addStockView(request):
    wineId = request.POST.get('addStock')
    if 'addStock' in request.POST:
        wine = get_object_or_404(Wine, idwine=int(wineId))
    userId = request.user.id
    user = get_object_or_404(AuthUser, id=userId)
    if request.method == 'POST':
        #wineIdNew = request.COOKIES.get('wineIdToAdd')
        #wineNew = get_object_or_404(Wine, idwine=wineIdNew)
        form = StockForm(request.POST, initial={'fk_wine': wineNew.idwine, 'fk_auth_user': user.id})
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = StockForm(initial={'fk_wine': wine.id,
                                  'fk_auth_user': user.id})
    response = render(request, 'addToStock.html', {'form': form})
    response.set_cookie('wineIdToAdd', wineId)
    return response

forms.py:

class StockForm(forms.ModelForm):
    #fk_wine = ModelChoiceField(queryset=Wine.objects.all(),
      #                        widget=HiddenInput())
    #fk_auth_user = ModelChoiceField(queryset=AuthUser.objects.all(),
     #                          widget=HiddenInput())
    class Meta:
        model = UserWineStock
        fields = ['fk_auth_user', 'fk_wine', 'number']

can anyone help me with this..?

1

There are 1 answers

1
Daniel Roseman On

Yes, initial data is ignored when a form is bound to submitted data.

Instead of using initial here, you should exclude those two fields from the form and set them on the created object:

form = StockForm(request.POST)
if form.is_valid():
    item = form.save(commit=False)
    item.fk_wine = wine
    item.fk_auth_user = request.user
    item.save()
    return redirect('home')

(Also, please don't call your fields things like fk_auth_user. Just call it user.)