Home » Python » python – Multiple Input Values For Model Form-Exceptionshub

python – Multiple Input Values For Model Form-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am creating profiles for users and I want them to be able to select multiple tags using forms.ModelMultipleChoiceField which will be saved to their profile.

My models.py setup:

class ProfileTags(models.Model):
 description = models.CharField(max_length=300)

class Profile(models.Model):
 user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 name = models.CharField(max_length=50, blank=True)
 services_offered = models.ManyToManyField(ProfileTags)

Forms.py:

class ProfileUpdateForm(forms.ModelForm):
 ProfileTags = forms.ModelMultipleChoiceField(queryset=ProfileTags.objects.all())
 class Meta:
    model = Profile

Views.py:

def profile(request):
 if request.method == 'POST':
    p_form = ProfileUpdateForm(request.POST,request.FILES, instance=request.user.profile)
    if p_form.is_valid():
        p_form.save()
        messages.success(request, f'Your account has been updated!')
        return redirect('profile')

 else:
    p_form = ProfileUpdateForm(instance=request.user.profile)

 context = {
    'form': p_form
 }

 return render(request, 'users/profsettings.html', context)

I load in the tags in the ProfileTags model and this seems to have worked and I’m able to allow users to submit the tags and it’s saved in the DB successfully, however I am experiencing the following issues:

  1. instance=request.user.profile does not seem to work for the checkboxes. After submitting the form, if I go back to the form the boxes aren’t checked. I want users to be able to remove tags from their profile by simply unchecking a previously checked box – this may be a template issue as I’m manually rendering the fields, however:

  2. It doesn’t seem to be possible to delete the tags in the admin panel from a certain profile, I can only delete the choice instances from the ProfileTags model.

This makes me think the way I’m going about what I’m trying to achieve is wrong.

Is there a better way to do this? I simply want people to be able to check the tags they want to add to their profile (N.B. the tags are limited so it has to be a multiplechoice) but saving multiple inputs to one ModelField seems overly tricky?

How to&Answers: