[Answered ]-Save data from ChoiceField to database Django

1👍

The reason for the error is that when a new Playlist object is created, the user field must not be empty (you did not add null=True, and of course, would not make sense here if you did). Now the form validates because the form does not require the user field, only the playlists field. You have a couple of choices.

Option 1
Add the required field to your form (I haven’t tested this, please check the docs!):

class ChoosePlaylistForm(ModelForm):

    playlists = forms.ChoiceField(choices=())

    class Meta:
        model = Playlist
        fields = ('playlists', 'user',)   # NOTE THE CHANGE HERE

    def __init__(self, *args, request=None, **kwargs):
        super(ChoosePlaylistForm, self).__init__(*args, **kwargs)
        self.request = request
        self.user = request.user    # Add the user to the form

Option 2
Save the form as is using commit=False, then add the missing field before you save your model:

if request.method == "POST":
        form = ChoosePlaylistForm(request.POST, request=request)
        if form.is_valid():
            playlist = form.save(commit=False)    # NOTE THE CHANGE HERE
            playlist.user = request.user          # Add the user to the partial playlist
            playlist.save()                       # Now you can save the playlist
            
            messages.success(request, "Playlist successfully chosen")
            return HttpResponseRedirect('account')

Option 3
Add the field when you instantiate the form itself (I’m not sure my syntax is correct here):

form = ChoosePlaylistForm(request.POST, request=request, instance=request.user)

EDIT
Option 3 above does not seem to work. I believe this edit will:

form = ChoosePlaylistForm(request.POST, request=request, initial={'user': request.user})

Leave a comment