预先填充ModelMultipleChoiceField Django

时间:2018-04-22 01:39:44

标签: django django-models django-forms

我正在创建一个网站,允许用户关注股票并查看基于这些股票的文章。注册后,用户第一次关注Stock s。在此之后,我希望他们能够查看显示所有Stock以及他们关注的页面的页面。如何预填充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})

模板:

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

1 个答案:

答案 0 :(得分:1)

尝试指定stocks字段的初始值:

form = StockFollowForm(
    initial={'stocks': request.user.profile.followed_stocks.all()}
)

有关详情,请查看Django docs on providing initial values to a ModelForm