I'm trying to pass some initial data to the volume field in CourseForm
, but for some reason it won't work. The volume field is a ForeignKey
to a table in the database.
It doesn't give me errors; it just doesn't display any information.
My model with the respective volume field:
class Course(models.Model):
volume = models.ForeignKey(CourseVolume)
code = models.CharField(max_length=100, default=None)
# ... code shortend to simplify
My Modelform
with its model set to Course
class CourseForm(ModelForm):
class Meta:
model = Course
fields = '__all__'
My view where I'm trying to set the initial data for the CourseForm
. It just doesn't seem to work. user.volume_preference
returns an integer from 1 to x which is the id for the specific volume.
def view_course_create(request):
if request.method == 'POST':
form = CourseForm(request.POST)
if form.is_valid():
form.save()
return redirect('teaching_courses')
else:
user = MbsUser.get_user_from_ad(request.session['username'])
if user.volume_preference is not None:
volume = user.volume_preference
form = CourseForm(initial={'volume': volume})
else:
form = CourseForm()
return render(request, 'teaching/course_create.html', {'form': form})
My CourseVolume model:
class CourseVolume(CourseEnum):
published = models.BooleanField(default=False)
class Meta(CourseEnum.Meta):
db_table = 'mbs_course_volume'
How can this be solved?
Try to add a default value for the volume field. The value should be the existing id of the related table(CourseVolume).
volume = models.ForeignKey(CourseVolume, default=1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.