Python django.forms.modelformset_factory() Examples

The following are 15 code examples for showing how to use django.forms.modelformset_factory(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: SEMS   Author: urankajtazaj   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def grade_students(request, course_id):
    course = Course.objects.get(pk=course_id)
    curr_grades = Grade.objects.filter(course=course)

    queryset = Grade.objects.filter(course=course)

    GradeStudentsFormSet = forms.modelformset_factory(Grade, form=GradeStudentsForm, extra=0)

    if request.method == 'POST':
        formset = GradeStudentsFormSet(request.POST, queryset=queryset)
        if formset.is_valid():
            instances = formset.save(commit=False)
            for instance in instances:
                instance.save()
            return redirect('course_detail', pk=course_id)
        else:
            print(formset.errors)
    else:
        formset = GradeStudentsFormSet(queryset=queryset)

    return render (
        request, 'grade_students.html', {'formset': formset, 'course': course},
    )

# ######################################################## 
Example 2
Project: SEMS   Author: urankajtazaj   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def admin_view(request, afat_extra):

    if not afat_extra:
        afat_extra = 0

    queryset = afatet_provimeve.objects.all()
    AfatetFormSet = forms.modelformset_factory(afatet_provimeve, form=AfatetForm, extra=afat_extra)

    if request.method == 'POST':
        formset = AfatetFormSet(request.POST, queryset=queryset)
        if formset.is_valid():
            for instance in formset.forms:
                if instance.cleaned_data.get('emri'):
                    instance.save()
            return redirect('administrator', afat_extra=0)
        else: 
            print(formset.errors)
    else:
        formset = AfatetFormSet(queryset=queryset)

    return render (
        request, 'admin_panel.html', {'formset': formset, 'extra': afat_extra},
    ) 
Example 3
Project: djangoecommerce   Author: gileno   File: views.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def get_formset(self, clear=False):
        CartItemFormSet = modelformset_factory(
            CartItem, fields=('quantity',), can_delete=True, extra=0
        )
        session_key = self.request.session.session_key
        if session_key:
            if clear:
                formset = CartItemFormSet(
                    queryset=CartItem.objects.filter(cart_key=session_key)
                )
            else:
                formset = CartItemFormSet(
                    queryset=CartItem.objects.filter(cart_key=session_key),
                    data=self.request.POST or None
                )
        else:
            formset = CartItemFormSet(queryset=CartItem.objects.none())
        return formset 
Example 4
Project: GTDWeb   Author: lanbing510   File: forms.py    License: GNU General Public License v2.0 5 votes vote down vote up
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max, min_num=min_num,
                                   validate_min=validate_min)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet 
Example 5
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        site = Site.objects.get(pk=self.kwargs.get('id'))
        blueprints = site.blueprints.all()
        count = 10 - blueprints.count()
        ImageFormSet = modelformset_factory(BluePrints, form=BluePrintForm, extra=count, can_delete=True)
        formset = ImageFormSet(queryset=blueprints)
        return render(request, 'fieldsight/blueprints_form.html', {'site': site, 'formset': formset,'id': self.kwargs.get('id'),
                                                                   'blueprints':blueprints},) 
Example 6
Project: openhgsenti   Author: drexly   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max, min_num=min_num,
                                   validate_min=validate_min)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet 
Example 7
Project: askvitor   Author: sibtc   File: views.py    License: MIT License 5 votes vote down vote up
def edit_all_products(request):
    ProductFormSet = modelformset_factory(Product, fields=('name', 'price', 'category'), extra=0)
    data = request.POST or None
    formset = ProductFormSet(data=data, queryset=Product.objects.filter(user=request.user))
    for form in formset:
        form.fields['category'].queryset = Category.objects.filter(user=request.user)

    if request.method == 'POST' and formset.is_valid():
        formset.save()
        return redirect('products_list')

    return render(request, 'products/products_formset.html', {'formset': formset}) 
Example 8
Project: djangoBlog   Author: deepak2431   File: views.py    License: MIT License 5 votes vote down vote up
def askQuestion(request):
    #creating a set of forms for multiple images
    ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=6)

    #if request is POST, validate and save both the forms
    if request.method == 'POST':
        questionForm = QuestionForm(request.POST)
        formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none())

        if questionForm.is_valid() and formset.is_valid():
            new_question = Post()
            new_question.title = questionForm.cleaned_data['title']
            new_question.content = questionForm.cleaned_data['content']
            new_question.topic = questionForm.cleaned_data['topic']
            new_question.author = request.user
            new_question.isQuestion = True
            new_question.save()

            for form in formset.cleaned_data:
                if form:
                    image = form['image']
                    photo = Images(post=new_post, image=image)
                    photo.save()
            messages.success(request, "Posted!")
            return HttpResponseRedirect("/questions/form/")
        else:
            print(questionForm.errors, formset.errors)
    # if request is GET, display empty forms
    else:
        questionForm = QuestionForm()
        formset = ImageFormSet(queryset=Images.objects.none())
    
    context = {'postForm': questionForm, 'formset': formset, 'Q_Form':True}
    return render(request, 'blog/post_form.html', context) 
Example 9
Project: djangoBlog   Author: deepak2431   File: views.py    License: MIT License 5 votes vote down vote up
def createPost(request):
    #creating a set of forms for multiple images
    ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=6)

    #if request is POST, validate and save both the forms
    if request.method == 'POST':
        postForm = PostForm(request.POST)
        formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none())

        if postForm.is_valid() and formset.is_valid():
            new_post = Post()
            new_post.title = postForm.cleaned_data['title']
            new_post.content = postForm.cleaned_data['content']
            new_post.topic = postForm.cleaned_data['topic']
            new_post.author = request.user
            new_post.save()

            for form in formset.cleaned_data:
                if form:
                    image = form['image']
                    photo = Images(post=new_post, image=image)
                    photo.save()
            messages.success(request, "Posted!")
            return HttpResponseRedirect("/")
        else:
            print(postForm.errors, formset.errors)
    # if request is GET, display empty forms
    else:
        postForm = PostForm()
        formset = ImageFormSet(queryset=Images.objects.none())
    
    context = {'postForm': postForm, 'formset': formset}
    return render(request, 'blog/post_form.html', context) 
Example 10
Project: djangoBlog   Author: deepak2431   File: views.py    License: MIT License 5 votes vote down vote up
def updatePost(request,pk):
    ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=2)
    post = get_object_or_404(Post, pk=pk)
    old_images = Images.objects.filter(post=post)

    #check authorization of user
    if post.author != request.user:
        messages.success(request, "You are not authorized to update this post!")
        return HttpResponseRedirect("/")

    #if request is POST, update both the forms    
    if request.method == 'POST':
        postForm = PostForm(request.POST)
        formset = ImageFormSet(request.POST,request.FILES, queryset=Images.objects.none())
        if postForm.is_valid() and formset.is_valid() :
            post.title = postForm.cleaned_data['title']
            post.content = postForm.cleaned_data['content']
            post.topic = postForm.cleaned_data['topic']
            post.save()
            old_images.delete()
            for form in formset.cleaned_data:
                if form:
                    image = form['image']
                    photo = Images(post=post, image=image)
                    photo.save()
            messages.success(request, "Post Updated!")
            return HttpResponseRedirect("/")
        else:
            messages.success(request, "Post Not Updated! Upload all Images")
            return HttpResponseRedirect("/")
            
    #if request is GET, return both the forms with Initial values        
    else:
        postForm = PostForm(instance=post)
        formset = ImageFormSet(queryset=Images.objects.filter(post=post))
    
    context = {'postForm': postForm, 'formset': formset}
    return render(request,'blog/post_form.html', context) 
Example 11
Project: django-i18nfield   Author: raphaelm   File: test_forms.py    License: Apache License 2.0 5 votes vote down vote up
def test_modelformset_pass_locales_down():
    a = Author.objects.create(name='Tolkien')
    title = 'The Lord of the Rings'
    abstract = 'Frodo tries to destroy a ring'
    Book.objects.create(author=a, title=title, abstract=abstract)

    FormSetClass = modelformset_factory(Book, form=BookForm, formset=I18nModelFormSet)
    fs = FormSetClass(locales=['de', 'fr'], queryset=Book.objects.all())
    assert fs.forms[0].fields['title'].widget.enabled_locales == ['de', 'fr']
    assert fs.empty_form.fields['title'].widget.enabled_locales == ['de', 'fr'] 
Example 12
Project: Django-3-Web-Development-Cookbook-Fourth-Edition   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def add_or_change_idea(request, pk=None):
    idea = None
    if pk:
        idea = get_object_or_404(Idea, pk=pk)
    IdeaTranslationsFormSet = modelformset_factory(
        IdeaTranslations, form=IdeaTranslationsForm, extra=0, can_delete=True
    )
    if request.method == "POST":
        form = IdeaForm(request, data=request.POST, files=request.FILES, instance=idea)
        translations_formset = IdeaTranslationsFormSet(
            queryset=IdeaTranslations.objects.filter(idea=idea),
            data=request.POST,
            files=request.FILES,
            prefix="translations",
            form_kwargs={"request": request},
        )
        if form.is_valid() and translations_formset.is_valid():
            idea = form.save()
            translations = translations_formset.save(commit=False)
            for translation in translations:
                translation.idea = idea
                translation.save()
            translations_formset.save_m2m()
            for translation in translations_formset.deleted_objects:
                translation.delete()
            return redirect("ideas:idea_detail", pk=idea.pk)
    else:
        form = IdeaForm(request, instance=idea)
        translations_formset = IdeaTranslationsFormSet(
            queryset=IdeaTranslations.objects.filter(idea=idea),
            prefix="translations",
            form_kwargs={"request": request},
        )

    context = {"idea": idea, "form": form, "translations_formset": translations_formset}
    return render(request, "ideas/idea_form.html", context) 
Example 13
Project: Django-3-Web-Development-Cookbook-Fourth-Edition   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def add_or_change_idea(request, pk=None):
    idea = None
    if pk:
        idea = get_object_or_404(Idea, pk=pk)
    IdeaTranslationsFormSet = modelformset_factory(
        IdeaTranslations, form=IdeaTranslationsForm, extra=0, can_delete=True
    )
    if request.method == "POST":
        form = IdeaForm(request, data=request.POST, files=request.FILES, instance=idea)
        translations_formset = IdeaTranslationsFormSet(
            queryset=IdeaTranslations.objects.filter(idea=idea),
            data=request.POST,
            files=request.FILES,
            prefix="translations",
            form_kwargs={"request": request},
        )
        if form.is_valid() and translations_formset.is_valid():
            idea = form.save()
            translations = translations_formset.save(commit=False)
            for translation in translations:
                translation.idea = idea
                translation.save()
            translations_formset.save_m2m()
            for translation in translations_formset.deleted_objects:
                translation.delete()
            return redirect("ideas:idea_detail", pk=idea.pk)
    else:
        form = IdeaForm(request, instance=idea)
        translations_formset = IdeaTranslationsFormSet(
            queryset=IdeaTranslations.objects.filter(idea=idea),
            prefix="translations",
            form_kwargs={"request": request},
        )

    context = {"idea": idea, "form": form, "translations_formset": translations_formset}
    return render(request, "ideas/idea_form.html", context) 
Example 14
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
def post(self, request, id):
        site = Site.objects.get(pk=self.kwargs.get('id'))
        blueprints = site.blueprints.all()
        count = 10 - blueprints.count()
        ImageFormSet = modelformset_factory(BluePrints, form=BluePrintForm, extra=count, can_delete=True)
        formset = ImageFormSet(request.POST, request.FILES, queryset=blueprints)

        if formset.is_valid():
            instances = formset.save(commit=False)
            for item in instances:
                item.site_id = id
                item.save()

            try:
                # For Django 1.7+
                for item in formset.deleted_objects:
                    item.delete()
            except AssertionError:
                # Django 1.6 and earlier already deletes the objects, trying to
                # delete them a second time raises an AssertionError.
                pass

        return HttpResponseRedirect(reverse("fieldsight:site-blue-prints",
                                            kwargs={'id': id}))

        # if formset.is_valid():
        #     for form in formset.cleaned_data:
        #         if 'image' in form:
        #             image = form['image']
        #             photo = BluePrints(site_id=id, image=image)
        #             photo.save()
        #     messages.success(request,
        #                      "Blueprints saved!")
        #     site = Site.objects.get(pk=id)
        #     blueprints = site.blueprints.all()

        #     ImageFormSet = modelformset_factory(BluePrints, form=BluePrintForm, extra=5)
        #     formset = ImageFormSet(queryset=BluePrints.objects.none())
        #     return render(request, 'fieldsight/blueprints_form.html', {'site': site, 'formset': formset,'id': self.kwargs.get('id'),
        #                                                            'blueprints':blueprints},)

        #     # return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': id}))

        # formset = ImageFormSet(queryset=BluePrints.objects.none())
        # return render(request, 'fieldsight/blueprints_form.html', {'formset': formset, 'id': self.kwargs.get('id')}, ) 
Example 15
Project: eventoL   Author: eventoL   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def edit_event(request, event_slug):
    event = get_object_or_404(Event, event_slug=event_slug)
    event_form = EventForm(request.POST or None, prefix='event', instance=event)

    contacts_formset = modelformset_factory(Contact, form=ContactForm, can_delete=True)
    # pylint: disable=unexpected-keyword-arg
    contacts_formset = contacts_formset(
        request.POST or None, prefix='contacts-form',
        queryset=event.contacts.all())
    # pylint: enable=unexpected-keyword-arg

    event_date_formset = modelformset_factory(
        EventDate, form=EventDateForm,
        formset=EventDateModelFormset, can_delete=True)

    # pylint: disable=unexpected-keyword-arg
    event_date_formset = event_date_formset(
        request.POST or None, prefix='event-date-form',
        queryset=EventDate.objects.filter(event=event))
    # pylint: enable=unexpected-keyword-arg

    if request.POST:
        if event_form.is_valid() and contacts_formset.is_valid() and event_date_formset.is_valid():
            try:
                the_event = event_form.save()
                contacts = contacts_formset.save(commit=False)
                event_dates = event_date_formset.save(commit=False)

                for a_contact in contacts:
                    a_contact.event = the_event

                for event_date in event_dates:
                    event_date.event = the_event

                contacts_formset.save()
                event_date_formset.save()

                return redirect(reverse('index', args=[the_event.event_slug]))
            except Exception as error_message:
                logger.error(error_message)

        messages.error(
            request, _("There is a problem with your event. Please check the form for errors."))
    return render(
        request,
        'event/create.html',
        update_event_info(
            event_slug,
            {
                'form': event_form,
                'domain': request.get_host(),
                'protocol': request.scheme,
                'contacts_formset': contacts_formset,
                'event_date_formset': event_date_formset,
                'fields_dependencies': Event.get_fields_dependencies()
            }
        )
    )