我正在创建一个网站,允许用户关注股票并根据他们所关注的内容查看文章。我通过选择复选框创建了一个跟踪股票的页面,将该数据作为列表传递到stocks_user_selected
,但我不确定如何将信息保存到数据库。提前谢谢。
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.first_name
@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 follow_stocks_post_registration(request):
all_stocks = Stock.objects.all()
if request.method == 'POST':
stocks_user_selected = request.POST.getlist('stocks_selected')
for stock in stocks_user_selected:
request.user.profile.followed_stocks = request.user.profile.followed_stocks + stock #???
return render(request, 'core/post_registration_stock_following.html', {'all_stocks': all_stocks})
用于获取数据的表单:
{% block head %}
<title>Next step follow stocks</title>
{% endblock %}
{% block body %}
<form action ="{% url 'follow_stocks_post_registration' %}" method="post" >
{% csrf_token %}
{% for stock in all_stocks %}
<input type="checkbox" value="{{ stock.name }}" name="stocks_selected">{{ stock }}
<br/>
{% endfor %}
<button type = "submit" value="Submit"></button>
</form>
{% endblock %}
答案 0 :(得分:0)
您要发布所选股票的名称,因此请按名称加载每个股票,然后使用add()
方法将其添加到if request.method == 'POST':
stocks_user_selected = request.POST.getlist('stocks_selected')
user_profile = request.user.profile
for stock_name in stocks_user_selected:
stock = Stock.objects.get(name=stock_name)
user_profile.followed_stocks.add(stock)
user_profile.save()
。
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })