Python django.forms.models.modelformset_factory() Examples

The following are 9 code examples of django.forms.models.modelformset_factory(). 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 also want to check out all available functions/classes of the module django.forms.models , or try the search function .
Example #1
Source File: forms.py    From gazetteer with MIT License 6 votes vote down vote up
def add_fields(self, form, index):
        super(BaseRelationsFormSet, self).add_fields(form, index)
        form.fields["feature2"] = AutoCompleteSelectField('feature', required=False)

# pass in the base formset class to the factory
# RelationFormSet = modelformset_factory(Relationship,fields=('feature2','relationship_type'),extra=1,formset=BaseRelationsFormSet) 
Example #2
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def manage_common_problems(request, course_slug, activity_slug):    
    with django.db.transaction.atomic():
        error_info = None
        course = get_object_or_404(CourseOffering, slug = course_slug)
        activity = get_object_or_404(NumericActivity, offering = course, slug = activity_slug, deleted=False) 
       
        fields = ('activity_component', 'title', 'description', 'penalty', 'deleted',)
        
        CommonProblemFormSet = modelformset_factory(CommonProblem, fields=fields, \
                                                  formset=BaseCommonProblemFormSet, \
                                                  can_delete = False, extra = 3) 
        # get the components of this activity
        components = activity.activitycomponent_set.filter(deleted = False)
        # only need the common problems associated with these components 
        qset =  CommonProblem.objects.filter(activity_component__in=components, deleted=False);   
                     
        if request.method == "POST":     
            formset = CommonProblemFormSet(components, request.POST, queryset = qset)
            
            if not formset.is_valid(): 
                if formset.non_form_errors(): # not caused by error of an individual form
                    error_info = formset.non_form_errors()[0] 
            else:       
                # save the formset  
                _save_common_problems(formset, activity, request.user.username)
                messages.add_message(request, messages.SUCCESS, 'Common problems Saved')
                return HttpResponseRedirect(reverse('offering:marking:manage_common_problems', kwargs={'course_slug': activity.offering.slug, 'activity_slug': activity.slug}))
        else: # for GET request     
            formset = CommonProblemFormSet(components, queryset = qset) 
        
        if error_info:
            messages.add_message(request, messages.ERROR, error_info)    
        return render(request, "marking/common_problems.html", 
                                  {'course' : course, 'activity' : activity, 
                                  'components': components, 'formset' : formset }) 
Example #3
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def attachment_formset_factory():
    return modelformset_factory(DocumentAttachment, form=AttachmentForm, extra=1) 
Example #4
Source File: util.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def process_modelformset(request, model_class, queryset, **kwargs):
    """With the Django model class `model_class` and the given `queryset`,
    construct a formset process its submission.
    """

    # Create a formset class for the model `model_class` (i.e. it will contain
    # forms whose contents are based on the fields of `model_class`);
    # parameters for the construction of the forms used in the formset should
    # be in kwargs.
    formset_class = modelformset_factory(model_class, **kwargs)

    if queryset is None:
        queryset = model_class.objects.all()

    # If the request is a POST, we want to possibly update our data
    if request.method == "POST" and request.POST:
        # Create a formset from all the 'model_class' instances whose values
        # will be updated using the contents of request.POST
        objects = paginate(request, queryset)
        formset = formset_class(request.POST, queryset=objects.object_list)

        # Validate all the forms in the formset
        if formset.is_valid():
            # If all is well, Django can save all our data for us
            formset.save()
        else:
            # Otherwise, complain to the user that something went wrong
            return (
                formset,
                _("There are errors in the form. Please review " "the problems below."),
                objects,
            )

        # Hack to force reevaluation of same query
        queryset = queryset.filter()

    objects = paginate(request, queryset)

    return formset_class(queryset=objects.object_list), None, objects 
Example #5
Source File: forms.py    From connect with MIT License 5 votes vote down vote up
def get_subscription_formset(user):
    """Create a subscription formset for a user."""
    # pylint: disable=invalid-name
    SubscriptionModelFormSet = modelformset_factory(
        Subscription, form=SubscriptionForm, extra=0, can_delete=False)
    subscription_formset = SubscriptionModelFormSet(
        queryset=Subscription.objects.filter(
            user=user).select_related('group__group', 'group__category'))
    for form in subscription_formset:
        if hasattr(form, 'instance'):
            form.group_name = form.instance.group.group.name
    return subscription_formset 
Example #6
Source File: __init__.py    From django_reverse_admin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reverse_inlineformset_factory(parent_model,
                                  model,
                                  parent_fk_name,
                                  form=ModelForm,
                                  fields=None,
                                  exclude=None,
                                  formfield_callback=lambda f: f.formfield()):

    if fields is None and exclude is None:
        related_fields = [f for f in model._meta.get_fields() if
                          (f.one_to_many or f.one_to_one or f.many_to_many) and f.auto_created and not f.concrete]
        fields = [f.name for f in model._meta.get_fields() if f not in
                  related_fields]  # ignoring reverse relations
    kwargs = {
        'form': form,
        'formfield_callback': formfield_callback,
        'formset': ReverseInlineFormSet,
        'extra': 0,
        'can_delete': True,
        'can_order': False,
        'fields': fields,
        'exclude': exclude,
        'max_num': 1,
    }
    FormSet = modelformset_factory(model, **kwargs)
    FormSet.parent_fk_name = parent_fk_name
    return FormSet 
Example #7
Source File: django_reverse_admin.py    From django_reverse_admin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reverse_inlineformset_factory(parent_model,
                                  model,
                                  parent_fk_name,
                                  form=ModelForm,
                                  fields=None,
                                  exclude=None,
                                  formfield_callback=lambda f: f.formfield()):

    if fields is None and exclude is None:
        related_fields = [f for f in model._meta.get_fields() if
                          (f.one_to_many or f.one_to_one or f.many_to_many) and f.auto_created and not f.concrete]
        fields = [f.name for f in model._meta.get_fields() if f not in
                  related_fields]  # ignoring reverse relations
    kwargs = {
        'form': form,
        'formfield_callback': formfield_callback,
        'formset': ReverseInlineFormSet,
        'extra': 0,
        'can_delete': True,
        'can_order': False,
        'fields': fields,
        'exclude': exclude,
        'max_num': 1,
    }
    FormSet = modelformset_factory(model, **kwargs)
    FormSet.parent_fk_name = parent_fk_name
    return FormSet 
Example #8
Source File: views.py    From coursys with GNU General Public License v3.0 4 votes vote down vote up
def manage_activity_components(request, course_slug, activity_slug):    
    with django.db.transaction.atomic():
        error_info = None
        course = get_object_or_404(CourseOffering, slug = course_slug)   
        activity = get_object_or_404(NumericActivity, offering = course, slug = activity_slug, deleted=False)
        if activity.quiz_marking():
            messages.add_message(request, messages.INFO, 'This activity is marked as a quiz: redirecting you there.')
            return redirect('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
        fields = ('title', 'description', 'max_mark', 'deleted',)
        ComponentsFormSet  = modelformset_factory(ActivityComponent, fields=fields, \
                                                  formset=BaseActivityComponentFormSet, \
                                                  can_delete = False, extra = 25) 
        
        qset = ActivityComponent.objects.filter(numeric_activity = activity, deleted=False)
                     
        if request.method == "POST":     
            formset = ComponentsFormSet(activity, request.POST, queryset = qset)
            
            if not formset.is_valid(): 
                if formset.non_form_errors(): # not caused by error of an individual form
                    error_info = formset.non_form_errors()[0] 
            else:          
                # save the formset  
                now_max = _save_components(formset, activity, request.user.username)
                messages.add_message(request, messages.SUCCESS, 'Components of %s Saved!' % activity.name)
                # if the max grade changed
                if now_max != activity.max_grade: 
                    old_max = activity.max_grade
                    activity.max_grade = now_max
                    activity.save()               
                    messages.add_message(request, messages.WARNING, \
                                         "The max grade of %s updated from %s to %s" % (activity.name, old_max, now_max))
               
                return _redirct_response(request, course_slug, activity_slug)            
        else: # for GET request
            formset = ComponentsFormSet(activity, queryset = qset) 
        
        if error_info:
            messages.add_message(request, messages.ERROR, error_info)
        return render(request, "marking/components.html", 
                                  {'course' : course, 'activity' : activity,\
                                   'formset' : formset }) 
Example #9
Source File: monsters.py    From swarfarm with Apache License 2.0 4 votes vote down vote up
def monster_instance_bulk_add(request, profile_name):
    return_path = reverse('herders:profile_default', kwargs={'profile_name': profile_name})
    try:
        summoner = Summoner.objects.select_related('user').get(user__username=profile_name)
    except Summoner.DoesNotExist:
        return HttpResponseBadRequest()

    is_owner = (request.user.is_authenticated and summoner.user == request.user)

    BulkAddFormset = modelformset_factory(MonsterInstance, form=BulkAddMonsterInstanceForm, formset=BulkAddMonsterInstanceFormset, extra=5, max_num=50)

    if request.method == 'POST':
        formset = BulkAddFormset(request.POST)
    else:
        formset = BulkAddFormset()

    context = {
        'profile_name': request.user.username,
        'return_path': return_path,
        'is_owner': is_owner,
        'bulk_add_formset_action': request.path + '?next=' + return_path,
        'view': 'profile',
    }

    if is_owner:
        if request.method == 'POST':
            if formset.is_valid():
                new_instances = formset.save(commit=False)
                for new_instance in new_instances:
                    try:
                        if new_instance.monster:
                            new_instance.owner = summoner

                            if new_instance.monster.archetype == Monster.TYPE_MATERIAL:
                                new_instance.priority = MonsterInstance.PRIORITY_DONE

                            new_instance.save()
                            messages.success(request, 'Added %s to your collection.' % new_instance)
                    except ObjectDoesNotExist:
                        # Blank form, don't care
                        pass

                return redirect(return_path)
    else:
        raise PermissionDenied("Trying to bulk add to profile you don't own")

    context['bulk_add_formset'] = formset
    return render(request, 'herders/profile/monster_inventory/bulk_add_form.html', context)