获取复选框数据并将其保存到数据库django

时间:2018-04-20 23:16:01

标签: django django-models django-forms django-templates django-views

我正在创建一个网站,用户可以根据他们关注的内容关注股票和查看文章。我正在努力获得允许用户选择他们想要关注哪些股票的观点。

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())

模板:

{%  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})

这会成功显示复选框旁边所有Stock的表单,但如何从复选框中实际捕获数据并将其保存到test视图中的数据库?

1 个答案:

答案 0 :(得分:0)

您要在视图中保存用户,但由于字段followed_stocks位于个人资料中,您可能还需要保存个人资料。

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

如果有帮助,请告诉我。