0

I have a form ReviewForm that extends ModelForm. ReviewForm's model is Review, which has the fields:

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

and for 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']

I'm trying to pass initial values to the form before rendering it. Here's my code for 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})

The initial values of prof and user are set successfully. I'm trying to pass in the courses of a prof, and have the form display that queryset. However, Django doesn't seem to accept it.

I'm not sure how to code this function. Setting the initial value of prof and user works because it selects the initial value. I'm sure that the code to get a prof's courses: course = prof.course_set.all() works properly, I've tested it in shell. So what I need to do is set the possible values of the form's courses, based on the queryset input.

Gab De Jesus
  • 187
  • 1
  • 14

1 Answers1

0

Thanks to @solarissmoke for the link! I fixed it with:

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
Gab De Jesus
  • 187
  • 1
  • 14