如何使用ModelMultipleChoiceField

时间:2018-04-20 20:04:20

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

我正在尝试创建一个网站,允许用户关注某些股票,并根据他们所关注的内容阅读文章。我无法为他们创建表单以跟踪股票,因为用户ProfileStocks有很多关系,我相信我应该使用ModelMultipleChoiceField但是无法让它发挥作用。

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

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():
        stocks = forms.ModelMultipleChoiceField(queryset=Stock.objects.all())

views.py

def test(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})

模板:

{%  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'>Login</button>
            </div>

        </form>

    </div>

{% endblock %}

当我运行此代码时,不会显示任何表单。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我认为你的表单类必须继承djangos表单,比如docs show。

更改

class StockFollowForm():

from django import forms
class StockFollowForm(forms.Form):