2

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?

1
  • did you get to solve your problem? Was my answer below useful to you? Commented Apr 24, 2018 at 15:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.