Django Model Forms设置外键下拉列表的可能值

时间:2017-12-03 04:16:28

标签: python django django-forms django-views

我的表单ReviewForm扩展了ModelFormReviewForm的模型是Review,其中包含以下字段:

class Review(models.Model):
    message = models.TextField(max_length = 4000)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(null = True)
    rating = models.IntegerField(
        default = 5, 
        validators = [MaxValueValidator(5), MinValueValidator(0)]
    )
    prof = models.ForeignKey(Prof, related_name = 'reviews')
    course = models.ForeignKey(Course, related_name = 'reviews')
    user = models.ForeignKey(User, related_name = 'reviews')

forms.py

class ReviewForm(ModelForm):
    rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5}))

    class Meta:
        model = Review
        fields = ['message', 'rating', 'prof', 'course', 'user']

我尝试在呈现之前将初始值传递给表单。这是我views.py

的代码
def review(request, prof_id=None):
    """ Review a prof """
    # If there's an input prof, return review page for that prof
    if prof_id:
        user = User.objects.get(pk=request.user.id)
        prof = prof_views.prof(prof_id)
        course = prof.course_set.all()
        data = {'user': user, 'prof': prof, 'course': course}
        review_form = ReviewForm(initial=data)

        return render(request, 'reviews/review_form.html', {'review_form': review_form})
    review_form = ReviewForm()
    return render(request, 'reviews/review_form.html', {'review_form': review_form})

profuser的初始值已成功设置。我试图传递courses的{​​{1}},并让表单显示该查询集。然而,Django似乎并不接受它。

我不确定如何编写此功能。设置profprof的初始值有效,因为它选择了初始值。我确信获得专业课程的代码:user正常运行,我已经在shell中对其进行了测试。所以我需要做的是根据查询集输入设置表单课程的可能的值。

1 个答案:

答案 0 :(得分:0)

感谢@solarissmoke的链接!我修好了:

def review(request, prof_id=None):
    """ Review a prof """
    # If there's an input prof, return review page for that prof
    if prof_id:
        user = User.objects.get(pk=request.user.id)
        prof = prof_views.prof(prof_id)
        course = prof.course_set.all()
        data = {'user': user, 'prof': prof}
        review_form = ReviewForm(initial=data)
        review_form.fields['course'].queryset = course  # Added this line