justin o
justin o

Reputation: 33

Get checkbox data and save it to database django

I am creating a website where users can follow stocks and see articles based on what they follow. I am struggling to get the view that allows users to select which stocks they want to follow to work.

models.py

 from django.db import models
    from django.contrib.auth.models import User
    from django.dispatch import receiver
    from django.db.models.signals import post_save



    class Stock(models.Model):
        name = models.CharField(max_length = 50)
        ticker = models.CharField(max_length = 50)

        def __str__(self):
            return self.name

    class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        followed_stocks = models.ManyToManyField(Stock, blank=True)

        def __str__(self):
            return self.user.username

        @receiver(post_save, sender=User)
        def update_user_profile(sender, instance, created, **kwargs):
            if created:
                Profile.objects.create(user=instance)
            instance.profile.save()

    class Article(models.Model):
        stock = models.ForeignKey(Stock, on_delete=models.CASCADE, default = 0 )
        title = models.CharField(max_length = 200)
        url = models.URLField()
        description = models.TextField()

        def __str__(self):
            return self.title

forms.py:

class StockFollowForm(forms.Form):
    stocks = forms.ModelMultipleChoiceField(required =False,
                                           widget=forms.CheckboxSelectMultiple,
                                           queryset=Stock.objects.all())

template:

{%  block body %}
    <div class = "container">
        <h2 class = "text-center">Register</h2>

        <form method = 'post'>
            {% csrf_token %}
            {{ form }}
            <div class = "text-center">
                <br/>
                <button class="btn btn-primary" type = 'submit'>Follow</button>
            </div>

        </form>

    </div>

{% endblock %}

views.py:

 def follow_coins(request):
        if request.method == "POST":
            form = StockFollowForm(request.POST)
            if form.is_valid():
                request.user.profile.followed_stocks = form.cleaned_data.get('stocks_selected')
                request.user.save()
                return redirect('index')
        else:
            form = StockFollowForm()
            return render(request, 'core/test.html',{'form': form})

This succesfully displays a form of all Stocks next to checkboxes, but how do I actually capture the data from the checkbox and save it to my database in the test view?

Upvotes: 2

Views: 1769

Answers (1)

Ralf
Ralf

Reputation: 16495

You are saving the user in your view, but you probably need to save the profile as well since the field followed_stocks is in the profile.

request.user.save()
request.user.profile.save()   # add this line

Let me know if that helps.

Upvotes: 1

Related Questions