Python django.forms.inlineformset_factory() Examples

The following are 10 code examples for showing how to use django.forms.inlineformset_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: django-phone-field   Author: VeryApt   File: tests.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_validate_inlineformset(self):
        FormSet = inlineformset_factory(Business, Employee, fields=('name', 'phone'))
        business = Business.objects.create(name='Some Business')
        emp_1 = Employee.objects.create(name='1', business=business, phone='4151112222')
        formset = FormSet({
            'employee_set-TOTAL_FORMS': '1',
            'employee_set-INITIAL_FORMS': '2',
            'employee_set-MIN_NUM_FORMS': '0',
            'employee_set-MAX_NUM_FORMS': '1000',
            'employee_set-0-name': 'Employee 1',
            'employee_set-0-phone_0': '415 111 2222',
            'employee_set-0-phone_1': '',
            'employee_set-0-id': str(emp_1.pk),
            'employee_set-0-business': str(business.pk)
        }, instance=business)
        formset.clean()
        self.assertTrue(formset.is_valid()) 
Example 2
Project: django-multiple-user-types-example   Author: sibtc   File: teachers.py    License: MIT License 5 votes vote down vote up
def question_change(request, quiz_pk, question_pk):
    # Simlar to the `question_add` view, this view is also managing
    # the permissions at object-level. By querying both `quiz` and
    # `question` we are making sure only the owner of the quiz can
    # change its details and also only questions that belongs to this
    # specific quiz can be changed via this url (in cases where the
    # user might have forged/player with the url params.
    quiz = get_object_or_404(Quiz, pk=quiz_pk, owner=request.user)
    question = get_object_or_404(Question, pk=question_pk, quiz=quiz)

    AnswerFormSet = inlineformset_factory(
        Question,  # parent model
        Answer,  # base model
        formset=BaseAnswerInlineFormSet,
        fields=('text', 'is_correct'),
        min_num=2,
        validate_min=True,
        max_num=10,
        validate_max=True
    )

    if request.method == 'POST':
        form = QuestionForm(request.POST, instance=question)
        formset = AnswerFormSet(request.POST, instance=question)
        if form.is_valid() and formset.is_valid():
            with transaction.atomic():
                form.save()
                formset.save()
            messages.success(request, 'Question and answers saved with success!')
            return redirect('teachers:quiz_change', quiz.pk)
    else:
        form = QuestionForm(instance=question)
        formset = AnswerFormSet(instance=question)

    return render(request, 'classroom/teachers/question_change_form.html', {
        'quiz': quiz,
        'question': question,
        'form': form,
        'formset': formset
    }) 
Example 3
Project: django-blog-it   Author: MicroPyramid   File: views.py    License: MIT License 5 votes vote down vote up
def form_valid(self, form):
        self.blog_post = form.save(commit=False)
        formset = inlineformset_factory(
            Post, Post_Slugs, can_delete=True, extra=3, fields=('slug', 'is_active'),
            formset=CustomBlogSlugInlineFormSet)
        formset = formset(self.request.POST, instance=self.blog_post)
        if not formset.is_valid():
            return JsonResponse({'error': True, "response": formset.errors})
        self.blog_post.user = self.request.user
        if self.request.user.is_superuser:
            self.blog_post.status = self.request.POST.get('status')
        self.blog_post.save()
        self.blog_post.store_old_slug(self.blog_post.slug)
        formset.save()
        if self.request.POST.get('tags', ''):
            splitted = self.request.POST.get('tags').split(',')
            for s in splitted:
                blog_tags = Tags.objects.filter(name__iexact=s.strip())
                if blog_tags:
                    blog_tag = blog_tags.first()
                else:
                    blog_tag = Tags.objects.create(name=s.strip())
                self.blog_post.tags.add(blog_tag)

        self.blog_post.create_activity(user=self.request.user, content="added")
        messages.success(self.request, 'Successfully posted your blog')
        data = {'error': False, 'response': 'Successfully posted your blog',
                'title': self.request.POST['title']}
        return JsonResponse(data) 
Example 4
Project: django-blog-it   Author: MicroPyramid   File: views.py    License: MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(PostCreateView, self).get_context_data(**kwargs)
        tags_list = Tags.objects.all()
        categories_list = Category.objects.filter(is_active=True)
        context['status_choices'] = STATUS_CHOICE
        context['categories_list'] = categories_list
        context['tags_list'] = tags_list
        context['add_blog'] = True
        self.formset = inlineformset_factory(
            Post, Post_Slugs, can_delete=True, extra=3, fields=('slug', 'is_active'),
            formset=CustomBlogSlugInlineFormSet,
            widgets={'slug': forms.TextInput(attrs={'class': 'form-control'})})
        context['formset'] = self.formset()
        return context 
Example 5
Project: django-blog-it   Author: MicroPyramid   File: views.py    License: MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(PostEditView, self).get_context_data(**kwargs)
        categories_list = Category.objects.filter(is_active=True)
        context['status_choices'] = STATUS_CHOICE,
        context['categories_list'] = categories_list
        context['history_list'] = self.get_object().history.all()
        self.formset = inlineformset_factory(
            Post, Post_Slugs, can_delete=True, extra=3, fields=('slug', 'is_active'),
            formset=CustomBlogSlugInlineFormSet,
            widgets={'slug': forms.TextInput(attrs={'class': 'form-control'})})
        context['formset'] = self.formset(instance=self.get_object())
        return context 
Example 6
def test_module_formset_required_for_publish(phase_factory):
    class Form(forms.ModelForm):
        class Meta:
            model = phase_models.Phase
            fields = ['start_date']
            required_for_project_publish = ['start_date']
            widgets = {'start_date': forms.TextInput()}

    FormSet = inlineformset_factory(module_models.Module,
                                    phase_models.Phase,
                                    form=Form,
                                    formset=ModuleDashboardFormSet,
                                    extra=0,
                                    can_delete=False,
                                    )

    phase = phase_factory(module__project__is_draft=True)
    module = phase.module
    project = module.project
    phase_factory(module=module)

    formset = FormSet(instance=module)
    assert formset.get_required_fields() == ['start_date']
    assert all(map(lambda field: field.required is False,
                   [form.fields['start_date'] for form in formset.forms]))

    project.is_draft = False
    formset = FormSet(instance=module)
    assert formset.get_required_fields() == ['start_date']
    assert all(map(lambda field: field.required is True,
                   [form.fields['start_date'] for form in formset.forms])) 
Example 7
Project: elearning   Author: delitamakanda   File: teachers.py    License: MIT License 5 votes vote down vote up
def question_change(request, quiz_pk, question_pk):
    quiz = get_object_or_404(Quiz, pk=quiz_pk, owner=request.user)
    question = get_object_or_404(Question, pk=question_pk, quiz=quiz)
    AnswerFormSet = inlineformset_factory(
        Question,
        Answer,
        formset = BaseAnswerInlineFormSet,
        fields = ('text', 'is_correct'),
        min_num = 2,
        validate_min = True,
        max_num = 10,
        validate_max = True
    )

    if request.method == 'POST':
        form = QuestionForm(request.POST, instance=question)
        formset = AnswerFormSet(request.POST, instance=question)
        if form.is_valid() and formset.is_valid():
            with transaction.atomic():
                form.save()
                formset.save()
            messages.success(request, 'Question and answers saved with success!')
            return redirect('teacher_update_quiz', quiz.pk)
    else:
        form = QuestionForm(instance=question)
        formset = AnswerFormSet(instance=question)

    return render(request, 'students/teacher/question_change_form.html', {
        'quiz': quiz,
        'question': question,
        'form': form,
        'formset': formset
    }) 
Example 8
Project: django-i18nfield   Author: raphaelm   File: test_forms.py    License: Apache License 2.0 5 votes vote down vote up
def test_inlineformset_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 = inlineformset_factory(Author, Book, form=BookForm, formset=I18nInlineFormSet)
    fs = FormSetClass(locales=['de', 'fr'], instance=a)
    assert fs.forms[0].fields['title'].widget.enabled_locales == ['de', 'fr']
    assert fs.empty_form.fields['title'].widget.enabled_locales == ['de', 'fr'] 
Example 9
Project: django-blog-it   Author: MicroPyramid   File: views.py    License: MIT License 4 votes vote down vote up
def form_valid(self, form):
        formset = inlineformset_factory(
            Post, Post_Slugs, can_delete=True, extra=3, fields=('slug', 'is_active'), formset=CustomBlogSlugInlineFormSet)
        formset = formset(self.request.POST, instance=self.get_object())
        if not formset.is_valid():
            return JsonResponse({'error': True, "response": formset.errors})
        else:
            formset.save()
        previous_status = self.get_object().status
        previous_content = self.get_object().content
        self.blog_post = form.save(commit=False)
        # self.blog_post.user = self.request.user
        if self.request.user.is_superuser or get_user_role(self.request.user) != 'Author':
            self.blog_post.status = self.request.POST.get('status')
        else:
            self.blog_post.status = previous_status
        self.blog_post.save()
        self.blog_post.tags.clear()
        if self.request.POST.get('tags', ''):
            splitted = self.request.POST.get('tags').split(',')
            for s in splitted:
                blog_tags = Tags.objects.filter(name__iexact=s.strip())
                if blog_tags:
                    blog_tag = blog_tags.first()
                else:
                    blog_tag = Tags.objects.create(name=s.strip())
                self.blog_post.tags.add(blog_tag)
        if previous_content != self.blog_post.content:
            self.blog_post.create_activity(
                user=self.request.user, content=previous_content)
        # if self.blog_post.status == previous_status:
        #     self.blog_post.create_activity(
        #         user=self.request.user, content="updated")
        # else:
        #     self.blog_post.create_activity(
        #         user=self.request.user,
        #         content="changed status from " +
        #         str(previous_status) + " to " + str(blog_post.status)
        #     )
        self.blog_post.store_old_slug(self.kwargs.get("blog_slug"))
        messages.success(self.request, 'Successfully updated your blog post')
        data = {'error': False,
                'response': 'Successfully updated your blog post'}
        return JsonResponse(data) 
Example 10
def test_module_formset_component(phase_factory):
    class Form(forms.ModelForm):
        class Meta:
            model = phase_models.Phase
            fields = ['start_date']
            required_for_project_publish = ['start_date']
            widgets = {'start_date': forms.TextInput()}

    FormSet = inlineformset_factory(module_models.Module,
                                    phase_models.Phase,
                                    form=Form,
                                    formset=ModuleDashboardFormSet,
                                    extra=0,
                                    can_delete=False,
                                    )

    class Component(ModuleFormSetComponent):
        identifier = 'test_id'
        weight = 1
        label = 'Module Settings'

        form_title = 'Edit test module settings'
        form_class = FormSet
        form_template_name = 'none'

    phase = phase_factory(module__project__is_draft=True,
                          start_date=None)
    module = phase.module
    phase_factory(module=module, start_date=None)

    component = Component()
    assert component.is_effective(module) is True

    urls = component.get_urls()
    assert len(urls) == 1
    regexp, _, name = urls[0]
    assert regexp == r'^modules/(?P<module_slug>[-\w_]+)/test_id/$'
    assert name == 'dashboard-test_id-edit'

    assert component.get_progress(module) == (0, 2)

    phase.start_date = now()
    phase.save()
    assert component.get_progress(module) == (1, 2)