Opened 10 years ago

Last modified 10 years ago

#23404 closed Bug

Django modelformset returns the same data inserted in the previous insert when opening the same page for inserting new data — at Version 1

Reported by: Guruprasad Owned by: nobody
Component: Forms Version: 1.6
Severity: Normal Keywords: modelformset_factory
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Guruprasad)

# models.py
import datetime

from django.db import models


class Category(models.Model):
    category_name = models.CharField(unique=True, max_length=100)
    is_enabled = models.BooleanField(default=True)
    created_date = models.DateField(default=datetime.date.today)

    def __unicode__(self):
        return self.category_name

class Website(models.Model):
    url = models.URLField(unique=True)
    site_name = models.CharField(max_length=100)
    vertical_category = models.ForeignKey(Category, related_name="websites")
    unique_users_per_day = models.IntegerField()
    page_views_per_day = models.IntegerField()
    unique_users_per_month = models.IntegerField()
    page_views_per_month = models.IntegerField()

class Section(models.Model):
    website = models.ForeignKey(Website, related_name="sections")
    url = models.URLField(unique=True)
    section_name = models.CharField(max_length=100)

# forms.py
from django import forms
from django.forms.models import modelformset_factory, BaseModelFormSet
from .models import Website, Section


class AddWebsiteForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AddWebsiteForm, self).__init__(*args, **kwargs)
        self.fields['unique_users_per_day'].widget = forms.TextInput()
        self.fields['page_views_per_day'].widget = forms.TextInput()
        self.fields['unique_users_per_month'].widget = forms.TextInput()
        self.fields['page_views_per_month'].widget = forms.TextInput()
        self.fields['vertical_category'].empty_label = "Vertical Category"

    class Meta:
        model = Website
        exclude = []


class AddSectionForm(forms.ModelForm):
    class Meta:
        model = Section
        exclude = ['website',]


class FirstRequiredFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(FirstRequiredFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

AddSectionFormSet = modelformset_factory(Section, AddSectionForm, formset=FirstRequiredFormSet)

# views.py
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse_lazy
from django.forms.formsets import INITIAL_FORM_COUNT

from .forms import AddWebsiteForm, AddSectionFormSet

def add_website(request):
    import pdb; pdb.set_trace()
    if request.method == "POST":

        website_form = AddWebsiteForm(request.POST)
        section_formset = AddSectionFormSet(request.POST)

        if website_form.is_valid() and section_formset.is_valid():
            website = website_form.save()
            sections = section_formset.save(commit=False)

            for section in sections:
                section.website = website
                section.save()

            if 'add_another' in request.POST:
                return redirect(reverse_lazy('login'))
            else:
                return redirect(reverse_lazy('login'))
    else:
        website_form = AddWebsiteForm()
        section_formset = AddSectionFormSet()

    return render(request,
                  "website/add.html",
                  {
                      "website_form" : website_form,
                      "section_formset": section_formset
                  })

<!--website/add.html -->
<form action="" method="post">
<div>
{{ website_form }}
</div>
<div>
{{ section_formset }}
</div>
<input type="submit" value="submit">

After submitting the form for the first time and inserting some data, I visit the same URL for inserting more data. But the form of section formset is pre-populated with the data inserted the previous time.

Change History (1)

comment:1 by Guruprasad, 10 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top