python - "save and add another" in Django (not admin): submit then pre-populate one field of form -


i have form, "results", 1 of fields, "subjectid", many-to-many because there's more 1 result each subject. want 1 of submit buttons let me save i've entered, redirect same form, unbound except many-to-many "subjectid" field stays same can enter more results subject.

edit: should have made clear wanted instance had selected in subjectid field stay same. posted code below seems working me

from models.py

 class resultsform(forms.modelform):      class meta:          model = models.results          fields = ['subjectid', # field want       # populate form when "save , add another"               'slidenum', # integerfield               'resulttype' ] # foreignkey 

from views.py

def addresults(request):     if request.method == 'post'          form = resultsform(request.post)          if form.is_valid():              form.save()          if 'save_and_add_another' in request.post:             subjectid = form.fields['subjectid']             prepop = {'subjectid' : subjectid}             form = resultsform(initial=prepop)             return render(request, 'slideadmin/addresults.html', {'form': form})         elif 'save_and_return' in request.post:             return httpresponseredirect('/home/')         else:         form = resultsform()     return render(request, 'slideadmin/addresults.html', {'form': form}) 

right when click on "save , add another" addresults form, error:

typeerror @ /slidebox/addresults  'modelmultiplechoicefield' object not iterable 

which happens when rendering {{ form.as_p }} in template.

edit: changes made views.py

    if 'save_and_add_another' in request.post:         subjectid = form.cleaned_data.get('subjectid')         form = resultsform(initial={'subjectid': subjectid})         return render(request, 'slideadmin/addresults.html', {'form': form}) 

as far can tell, change works. again

you should use form.cleaned_data.get('subjectid') versus pulling field directly post data. need pass in list of pk's m2m field.

your view can use touch of cleanup:

from django.core.urlresolvers import reverse   def addresults(request):     form = resultsform(request.post or none)      if request.method == 'post' , form.is_valid():         form.save()          if 'save_and_add_another' in request.post:             subjectid = form.cleaned_data.get('subjectid', [])             if subjectid:                 subjectid = subjectids.split(',')             form = resultsform(initial={'subjectid': subjectid})          elif 'save_and_return' in request.post:             return httpresponseredirect(reverse('home'))  # don't hard code      return render(request, 'slideadmin/addresults.html', {'form': form}) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -