Reputation: 33
I am creating a website that allows users to follow stocks and see articles based on those stocks. Upon registration the user follows Stock
s for the first time. After this I would like them to be able to view a page that shows all Stock
s and which ones they follow. How can I prepopulate a ModelMultipleChoiceField?
models.py:
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()
views.py:
def test(request):
if request.method == "POST":
form = StockFollowForm(request.POST)
if form.is_valid():
request.user.profile.followed_stocks = list(form.cleaned_data.get('stocks_selected'))
request.user.profile.save()
return redirect('index')
else:
form = StockFollowForm() #how do I prepopulate this if there are already followed Stock objects
return render(request, 'core/test.html',{'form': form})
template:
<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/Unfollow Stocks</button>
</div>
</form>
</div>
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Stock
from django.forms import ModelMultipleChoiceField
class ProfileRegistrationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'email', 'first_name' ,'last_name')
class StockFollowForm(forms.Form):
stocks = forms.ModelMultipleChoiceField(required =False,
widget=forms.CheckboxSelectMultiple,
queryset=Stock.objects.all())
Upvotes: 1
Views: 483
Reputation: 4354
Try specifying the initial value for the stocks
field:
form = StockFollowForm(
initial={'stocks': request.user.profile.followed_stocks.all()}
)
For more on this, check out the Django docs on providing initial values to a ModelForm
Upvotes: 2