I want to load in a MultipleChoiceField as initial data a field with a manytomany relation, after save it.
My classes
class Course(models.Model):
name = models.CharField(max_length=30)
description = models.TextField(max_length=30)
owner = models.ForeignKey(User)
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='student')
courses_list = models.ManyToManyField(Course, blank=True)
My form
class AddSubscibeForm(forms.ModelForm):
userprofile_set = forms.ModelMultipleChoiceField(initial = User.objects)
class Meta:
model = Course
My view
def addstudents(request, Course_id):
editedcourse = Course.objects.get(id=Course_id) # (The ID is in URL)
form = AddSubscibeForm(instance=editedcourse)
return render(request, 'addstudents.html', locals())
Actually, I have a multiplechoicelist with users, but i don’t have the list of users that have the course in their ‘courses_list’ field..
I can access to the user’s cours_list by a :
> editedcourse = Course.objects.get(id=Course_id)
> subscribed = editedcourse.userprofile_set.all()
> subscribed.user.username
If you have an idea.. 🙂
To confirm what you’re asking. You want to be able to see a form with a Course and choose which Users have that course in their courses?
You will NOT be able to properly use a field in a ModelForm that does not exist in its Model.
What you can do is change the model and have a ManyToManyField pointing both ways and then use the following:
This would work assuming you have a ManyToManyField in
CoursescalleduserProfiles.To get the ManyToManyField to work both ways, take a look at this ticket.
I haven’t tried this but I think it should work.
or this:
Both of the above should work. And in both cases you shouldn’t have to change anything in the database.