Django模型表单设置了外键下拉的可能值

我有一个表格ReviewForm,它扩展ModelFormReviewForm的模型是Review,它具有以下字段:Django模型表单设置了外键下拉的可能值

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成功设置的初始值的代码。我试图传入profcourses,并以表单显示queryset。但是,Django似乎并不接受它。

我不知道如何编码此功能。设置profuser的初始值可以工作,因为它选择初始值。我确信获得教授课程的代码:course = prof.course_set.all()正常工作,我已经在shell中测试过它。所以我需要做的是根据queryset输入设置表格的课程的值可能的值。

回答:

感谢@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

以上是 Django模型表单设置了外键下拉的可能值 的全部内容, 来源链接: utcz.com/qa/259452.html

回到顶部