Django manyToManyField initial value based on another object using Formwizard
I have the model below:
class DrawingRevision(models.Model):
revision = models.CharField(max_length = 10)
previous_revision = models.ForeignKey('self', blank=True, null=True)
drawing = models.ForeignKey(Drawing)
part = models.ManyToManyField(Part, blank=True, null=True)
I have a formWizard which allows the user to select previous_revision. I would like to be able to have the list of parts from previous_revision already selected when the user gets to the last page of the formWizard. My thought is to do this in the ModelForm for DrawingRevision, but I'm not really sure how to go about that.
class DrawingRevisionForm(forms.ModelForm):
class Meta:
model = DrawingRevision
exclude = ('drawing','revision', 'previous_revision',)
def __init__(self, *args, **kwargs):
self(DrawingRevisoinForm, self).__init__(*args, **kwargs)
self.fields['revision_date'].widget = widgets.AdminDateWidget()
Thanks for your 开发者_JAVA技巧help!
EDIT:
I've made some progress with this. In my formwizard class, I have the following process_step method defined. It gets called just before I need to display the manytomany field with the initial values set. Below, 'd' is the list of parts from the previous drawing and nextform should be the form to be displayed (although type(self.form_list[1]) tells me its a declarativefieldsmetaclass). What I need to do is get the list of parts (d) to be the initial values for the next pages parts field.
def process_step(self, request, form, step):
if step == 1:
d = DrawingRevision.objects.filter(id__exact=request.POST['0-prerev'])[0].part.all()
nextform = self.form_list[1]
EDIT 2: I'm making a little more progress with this. I think that I need to set the initial member of the DrawingRevision form to something like:
nextform.initial = {'part': [DrawingRevision.objects.filter(id__exact=request.POST['0-prerev'])[0].part.all()], }
probably in parse_params(). But when I do this, the initial values are not selected on the last form, but rather everything is deselected.
I added this in parse_params() and it worked!:
if request.method == 'POST' and current_step == 1:
form = self.get_form(current_step, request.POST)
if form.is_valid():
self.initial[(current_step + 1)] = {'part': DrawingRevision.objects.filter(id__exact=request.POST['0-prerev'])[0].part.all(), }
I hope somebody finds this useful.
精彩评论