Django: ModelFormSet saving first entry only -
update:
the issue seemed in coding django-formset. processing inline formset , not model formset. answer below correct. thanks!
i working model formset intermediate model. using django-formset js add additional formset fields on template. works ok except when go save formset first entry being saved db. first entry saved , assigned correctly after disappear. not throwing errors not sure going wrong. thanks!
the model
class staffassignment(models.model): study = models.foreignkey(study, related_name='study_set', null=true, on_delete=models.cascade) staff = models.foreignkey('account.userprofile', related_name='assigned_to_set', null=true, on_delete=models.cascade) role = models.charfield(max_length=100, null=true) assigned_on = models.datetimefield(auto_now_add=true) class meta: ordering = ('-role',) def __str__(self): return '{} assigned {}'.format(self.staff, self.study)
the form:
class addstaff(forms.modelform): model = staffassignment fields = ('staff',) def __init__(self, *args, **kwargs): super(addstaff, self).__init__(*args, **kwargs) field in self.fields: self.fields[field].widget.attrs.update({'class': 'form-control'})
the view:
def add_staff(request, study_slug): study = get_object_or_404(study, slug=study_slug) staff_formset = modelformset_factory(staffassignment, form=addstaff, fields=('staff',), can_delete=true) if request.method == 'post': stafflist = staff_formset(request.post, request.files) if stafflist.is_valid(): assignment in stafflist: assigned = assignment.save(commit=false) assigned.study = study assigned.role = assigned.staff.job_title assigned.save() return httpresponseredirect(reverse('studies:studydashboard')) else: httpresponse('something messed up') else: stafflist = staff_formset(queryset=staffassignment.objects.none()) return render(request, 'studies/addstaff.html', {'stafflist': stafflist, 'study': study})
the template:
<form action="{% url 'studies:addstaff' study.slug %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="box-body"> {% list in stafflist %} <div class="form-group" id="formset"> {% if list.instance.pk %}{{ list.delete }}{% endif %} {{ list.staff }} {% if list.staff.errors %} {% error in list.staff.errors %} {{ error|escape }} {% endfor %} {% endif %} </div> {% endfor %} {{ stafflist.management_form }} </div> <div class="box-footer"> <button type="submit" class="btn btn-primary">submit</button> </div> </form>
you not including primary key field in template, required docs. add
{% list in stafflist %} {{ list.pk }} ... {% endfor %}
Comments
Post a Comment