當前位置: 首頁>>代碼示例>>Python>>正文


Python forms.modelformset_factory方法代碼示例

本文整理匯總了Python中django.forms.modelformset_factory方法的典型用法代碼示例。如果您正苦於以下問題:Python forms.modelformset_factory方法的具體用法?Python forms.modelformset_factory怎麽用?Python forms.modelformset_factory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.forms的用法示例。


在下文中一共展示了forms.modelformset_factory方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: grade_students

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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},
    )

# ######################################################## 
開發者ID:urankajtazaj,項目名稱:SEMS,代碼行數:27,代碼來源:views.py

示例2: admin_view

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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},
    ) 
開發者ID:urankajtazaj,項目名稱:SEMS,代碼行數:25,代碼來源:views.py

示例3: get_formset

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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 
開發者ID:gileno,項目名稱:djangoecommerce,代碼行數:20,代碼來源:views.py

示例4: generic_inlineformset_factory

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:38,代碼來源:forms.py

示例5: get

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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},) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:10,代碼來源:views.py

示例6: generic_inlineformset_factory

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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 
開發者ID:drexly,項目名稱:openhgsenti,代碼行數:38,代碼來源:forms.py

示例7: edit_all_products

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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}) 
開發者ID:sibtc,項目名稱:askvitor,代碼行數:14,代碼來源:views.py

示例8: askQuestion

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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) 
開發者ID:deepak2431,項目名稱:djangoBlog,代碼行數:36,代碼來源:views.py

示例9: createPost

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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) 
開發者ID:deepak2431,項目名稱:djangoBlog,代碼行數:35,代碼來源:views.py

示例10: updatePost

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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) 
開發者ID:deepak2431,項目名稱:djangoBlog,代碼行數:40,代碼來源:views.py

示例11: test_modelformset_pass_locales_down

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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'] 
開發者ID:raphaelm,項目名稱:django-i18nfield,代碼行數:12,代碼來源:test_forms.py

示例12: add_or_change_idea

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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) 
開發者ID:PacktPublishing,項目名稱:Django-3-Web-Development-Cookbook-Fourth-Edition,代碼行數:38,代碼來源:views.py

示例13: post

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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')}, ) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:47,代碼來源:views.py

示例14: edit_event

# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import modelformset_factory [as 別名]
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()
            }
        )
    ) 
開發者ID:eventoL,項目名稱:eventoL,代碼行數:60,代碼來源:views.py


注:本文中的django.forms.modelformset_factory方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。