How to get Checkbox Select Multiple for profile page

Viewed 38

Beginner here in Django.

Goal: I would like to get a multiple checkbox selection for favorite categories and save those in the database.

Problem Right now I have a profile form and model, and the CheckboxSelectMultiple widget is not working like I want it to work. The categories are stored in another model which I reference in the user profile.

# # # # user/forms/profile_form.py
class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        exclude = [ 'id', 'user']
        widgets = {
            'favourite_categories': widgets.CheckboxSelectMultiple(attrs={'class': 'form-control'}),
            'profile_picture': widgets.TextInput(attrs={'class': 'form-control'})
        }


# # # # user/models.py
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=200, blank=True)
    last_name = models.CharField(max_length=200, blank=True)
    favorite_categories = models.ManyToManyField(Category, blank=True)
    profile_image = models.CharField(max_length=200, null=True, blank=True)


# # # # user/views.py
@ login_required
def profile(request):
    user_profile = Profile.objects.filter(user=request.user).first()
    if request.method == 'POST':
        form = ProfileForm(instance=user_profile, data=request.POST)
        if form.is_valid():
            user_profile = form.save(commit=False)
            user_profile.user = request.user
            user_profile.save()
            return redirect('profile')
    return render(request,
                  'user/profile.html',
                  context={"form": ProfileForm(instance=user_profile)})


# # # # templates/user/profile.html
<div class="shadow p-4 mb-5 mx-5 bg-body rounded">
    <form class="form form-horizontal" method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <input type="submit" class="btn btn-primary" value="Update" />
    </form>
</div>

The output of this can be seen in the picture. Output of the current code.

PS. I also don't know how to use ImageField for inserting a profile image. I am using a google cloud database and the ImageField needs the variable upload_to, which specifies where the image will be uploaded to. I would like to store the image on the cloud database as all other data is.

1 Answers

It seems you'd have to write your own custom CheckboxSelectMultiple widget. You can see the answer of this post.

Related