I am using django modelformset_factory in one of my view. I am using javascript for adding new forms to the formset in Template. Everything is working fine but my problem is that when i try to create a new object using modelformset_factory it shows me all the objects as forms which i previously created. Or in simple words it shows me the last submitted forms when i create a new instance using modelformset_factory forms. Like I have defined extra = 0
while initializing the modelformset_factory and from template I added 5 forms to formset and submitted those. Next time when I will re render the template for creating calaendar for another user it show me all the instances which i submitted previously for the previous user. means It iwll show me 5 forms with full data which i submitted for previous user.
My model, Formset, Form and View are as follow.
class Calendar(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200, null=True, blank=True)
date = models.DateField(verbose_name=_('Date'))
def __unicode__(self):
return self.name
class UserCalendar(forms.ModelForm):
date =forms.DateField(input_formats=['%d-%m-%Y', '%d-%m-%y'])
class Meta:
model = ProviderCalendar
exclude = ('user',)
class CalendarFormset(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(CalendarFormset, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
def clean(self):
return super(CalendarFormset, self).clean()
class CreateCalendar(LoginRequiredMixin,DetailView):
model = Profile
template_name = 'calendar_create.html'
formset = modelformset_factory(Calendar,
form=CalendarForm,
formset=CalendarFormset,
extra=0,
)
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context = super(CreateCalendar, self).get_context_data(**kwargs)
context['formset'] = self.formset
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
formset = self.formset(request.POST)
self.object = self.get_object()
if formset.is_valid():
for form in formset.save(commit=False):
form.user = self.get_object().user
form.save()
messages.success(request, _('Calendar created successfully'))
return redirect("detail_profile")
else:
return self.render_to_response(self.get_context_data(formset=formset))
and my Next question is I want unique_together = (user, date). I have excluded the user field from forms so unique together forms validations will not work. Is there any way to check the unique dates for the submitted formset forms.
Answer of the first question i.e modelformset_factory always sustains the old data
is lies here.
https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#changing-the-queryset
as it is given in the docs chenge the queryset by overriding the constructor of the basemodelformset
from django.forms.models import BaseModelFormSet
from myapp.models import Author
class CalendarFormset(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(CalendarFormset, self).__init__(*args, **kwargs)
self.queryset = Calendar.objects.none()
It will solve the problem 1.
来源:https://stackoverflow.com/questions/29472751/django-modelformset-factory-sustains-the-previously-submitted-data-even-after-su