Exemple #1
0
def edit_recipe(request, pk):
    recipe = get_object_or_404(Recipe, pk=pk)
    if recipe.author.user != request.user:
        raise PermissionDenied

    StepFormSet = inlineformset_factory(Recipe, RecipeStep, fields=('body',),
            extra=1)

    IngredientFormSet = inlineformset_factory(Recipe, MeasuredIngredient,
            form=MeasuredIngredientForm, fields=('amount', 'units', 'ingredient'), extra=1)

    form = RecipeForm(request.POST or None, instance=recipe)
    form.stepsformset = StepFormSet(request.POST or None, request.FILES or None,
            instance=recipe)
    form.ingredientsformset = IngredientFormSet(request.POST or None, request.FILES or None,
            instance=recipe)

    if form.is_valid() and form.stepsformset.is_valid() and form.ingredientsformset.is_valid():
        form.save()
        form.stepsformset.save()
        form.ingredientsformset.save()

        return redirect('show_recipe', pk=recipe.pk)

    return render(request, 'edit_recipe.html', {'form':form})
Exemple #2
0
def add_grading_system(request, system_id=None):
    user = request.user
    grading_system = None
    if system_id is not None:
        grading_system = GradingSystem.objects.get(id=system_id)
    GradeRangeFormSet = inlineformset_factory(GradingSystem, GradeRange,
                                              fields='__all__', extra=0)
    grade_form = GradingSystemForm(instance=grading_system)
    is_default = (grading_system is not None and
                  grading_system.name == 'default')

    if request.method == 'POST':
        formset = GradeRangeFormSet(request.POST, instance=grading_system)
        grade_form = GradingSystemForm(request.POST, instance=grading_system)
        if grade_form.is_valid():
            system = grade_form.save(commit=False)
            system.creator = user
            system.save()
            system_id = system.id
        if formset.is_valid():
            formset.save()
        if 'add' in request.POST:
            GradeRangeFormSet = inlineformset_factory(
                GradingSystem, GradeRange, fields='__all__', extra=1
                )
    formset = GradeRangeFormSet(instance=grading_system)

    return render(request, 'add_grades.html',
                  {'formset': formset,
                   'grade_form': grade_form, "system_id": system_id,
                   'is_default': is_default}
                  )
Exemple #3
0
def create_recipe(request):

    StepFormSet = inlineformset_factory(Recipe, RecipeStep, fields=('body',),
            extra=1)

    IngredientFormSet = inlineformset_factory(Recipe, MeasuredIngredient,
            form=MeasuredIngredientForm, fields=('amount', 'units', 'ingredient'), extra=1)

    if request.method == 'POST':
        form = RecipeForm(request.POST)
        form.stepsformset = StepFormSet(request.POST, request.FILES)
        form.ingredientsformset = IngredientFormSet(request.POST, request.FILES)

        if form.is_valid() and form.stepsformset.is_valid() and form.ingredientsformset.is_valid():
            recipe = form.save(commit=False)
            recipe.author = request.user.profile
            recipe.save()

            form.stepsformset.instance = recipe
            form.stepsformset.save()

            form.ingredientsformset.instance = recipe
            form.ingredientsformset.save()

            return redirect('show_recipe', pk=recipe.pk)
    else:
        form = RecipeForm()
        form.stepsformset = StepFormSet()
        form.ingredientsformset = IngredientFormSet()

    return render(request, 'create_recipe.html', {'form':form})
Exemple #4
0
def reply_post(request, category, thread_id, parent_id):
    thread = get_object_or_404(Thread, category=category, id=thread_id)
    parent = get_object_or_404(Post, thread=thread, id=parent_id)

    MediaFormset = inlineformset_factory(Post, Media, fields=('image',),
                                         min_num=0, max_num=3, can_delete=False)
    AttachmentFormset = inlineformset_factory(Post, Attachment, fields=('file',),
                                              min_num=0, max_num=3, can_delete=False)

    if request.method == 'POST':
        post_form = PostReplyForm(data=request.POST)
        media_formset = MediaFormset(data=request.POST, files=request.FILES, prefix='media')
        attachment_formset = AttachmentFormset(data=request.POST, files=request.FILES, prefix='attachment')
    else:
        post_form = PostReplyForm(initial={'parent': parent, 'thread': thread})
        media_formset = MediaFormset(prefix='media')
        attachment_formset = AttachmentFormset(prefix='attachment')

    if post_form.is_valid() and media_formset.is_valid() and attachment_formset.is_valid():
        post = post_form.save(commit=False)
        media_set = media_formset.save(commit=False)
        attachment_set = attachment_formset.save(commit=False)

        post.author = Author.objects.get(pk=request.user.pk)
        post.is_approved = post.author.posts.filter(is_approved=True).exists() and not len(media_set) and not len(attachment_set)
        post.save()

        for media in media_set:
            media.post = post
            media.save()

        for attachment in attachment_set:
            attachment.post = post
            attachment.save()

        if not post.is_approved:
            notification_post_moderation_pending.apply_async(countdown=1, kwargs={'post_id': post.id, 'mode': 'approval'})
            messages.info(request, _('<strong>Thanks</strong>, your comment has successfully been submitted but requires approval.<br />' \
                                     'You will be informed via email once it has been reviewed and approved.'))
            return HttpResponseRedirect(reverse('comments:show_threads', kwargs={'category': category}))
        else:
            notification_post_new_reply.apply_async(countdown=1, kwargs={'post_id': post.id})
            messages.success(request, _('<strong>Thanks</strong>, your comment has successfully been submitted and posted.'))
            return HttpResponseRedirect(post.get_absolute_url())

    template_values = {
        'category': category,
        'post_form': post_form,
        'media_formset': media_formset,
        'attachment_formset': attachment_formset,
        'thread': thread,
        'parent': parent,
    }

    return render(request, 'edit_post.html', template_values)
Exemple #5
0
    def cl_formset(self):
        extra = 0
        kwargs = {}

        if self.copy_from and self.request.method != "POST":
            kwargs['initial'] = [
                {
                    'name': cl.name,
                    'all_products': cl.all_products,
                    'limit_products': cl.limit_products.all(),
                    'include_pending': cl.include_pending,
                } for cl in self.copy_from.checkinlist_set.prefetch_related('limit_products')
            ]
            extra = len(kwargs['initial'])
        elif not self.object and self.request.method != "POST":
            kwargs['initial'] = [
                {
                    'name': '',
                    'all_products': True,
                    'include_pending': False,
                }
            ]
            extra = 1

        formsetclass = inlineformset_factory(
            SubEvent, CheckinList,
            form=CheckinListForm, formset=CheckinListFormSet,
            can_order=False, can_delete=True, extra=extra,
        )
        if self.object:
            kwargs['queryset'] = self.object.checkinlist_set.prefetch_related('limit_products')

        return formsetclass(self.request.POST if self.request.method == "POST" else None,
                            instance=self.object,
                            event=self.request.event, **kwargs)
Exemple #6
0
    def formset(self):
        extra = 0
        kwargs = {}

        if self.copy_from and self.request.method != "POST":
            kwargs['initial'] = [
                {
                    'size': q.size,
                    'name': q.name,
                    'itemvars': [str(i.pk) for i in q.items.all()] + [
                        '{}-{}'.format(v.item_id, v.pk) for v in q.variations.all()
                    ]
                } for q in self.copy_from.quotas.prefetch_related('items', 'variations')
            ]
            extra = len(kwargs['initial'])

        formsetclass = inlineformset_factory(
            SubEvent, Quota,
            form=QuotaForm, formset=QuotaFormSet,
            can_order=False, can_delete=True, extra=extra,
        )
        if self.object:
            kwargs['queryset'] = self.object.quotas.prefetch_related('items', 'variations')

        return formsetclass(
            self.request.POST if self.request.method == "POST" else None,
            instance=self.object,
            event=self.request.event, **kwargs
        )
Exemple #7
0
def RfqCreateView(request):
    form = RfqForm(request.POST or None)
    RfqFormSet = inlineformset_factory(Rfq, Rfqlines, form=RfqlinesForm, extra=5, can_delete=True)
    lines_formset = RfqFormSet(request.POST or None, instance=form.instance)
    title = "Create a new RFQ"
    context = {
        "title": title,
        "form": form,
        "lines_formset": lines_formset,
    }
 
    if form.is_valid() and lines_formset.is_valid():
        rfq = form.save(commit=False)
        rfq.user = request.user
        rfq.save()
        lines_formset.save()
        rfq_list = Rfq.objects.order_by('rfq_id')[:20]
        title = "RFQ List"
        context = {
            "title": title,
            "rfq_list": rfq_list
        }
        return render(request, "rfq.html", context)
 
    return render(request, "rfq_create.html", context)
Exemple #8
0
 def formset(self):
     formsetclass = inlineformset_factory(
         Organizer, EventMetaProperty,
         form=EventMetaPropertyForm, can_order=False, can_delete=True, extra=0
     )
     return formsetclass(self.request.POST if self.request.method == "POST" else None,
                         instance=self.object, queryset=self.object.meta_properties.all())
    def test_empty_form(self):
        FormSet = inlineformset_factory(Poet, Poem, fields='__all__', formset=LazyChoiceInlineFormSet, extra=0)
        formset = FormSet()
        formset.lazy_model = Poem

        self.assertTrue(hasattr(formset.empty_form, 'lazy_model'))
        self.assertEqual(formset.empty_form.lazy_model, Poem)
Exemple #10
0
    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)
def _create_vrm_site_forms(site_list, VRM_acc, context_dict, exclude=[]):
    """
    Create forms for site importation from VRM
    """

    if not site_list['sites']:
       # Error with credentials
       return _return_error_import(request,context_dict,form,"check credentials")

    #create initial data for formset
    pre_pop_data = []

    for site in site_list['sites']:
        #get one and only vrm account
        #  remove sites that are already in the sesh_site
        if not site['name'] in exclude:
            site_model_form = {'site_name':site['name'],
                                'vrm_site_id':site['idSite'],
                                'has_genset': site['hasGenerator'],
                                'vrm_account': VRM_acc
                                }
            pre_pop_data.append(site_model_form)

    # Create form factory
    site_forms_factory = inlineformset_factory(VRM_Account,Sesh_Site,
            extra=len(pre_pop_data),form=SiteForm,
            exclude=('vrm_account','rmc_account'),
            can_delete= False
            )
    site_forms_factory = site_forms_factory(initial = pre_pop_data)
    context_dict['site_forms'] = site_forms_factory
    return  context_dict
Exemple #12
0
def items(request):
    StoreItemFormSet = inlineformset_factory(
        parent_model=StoreItem, model=StoreItemVariant, form=StoreItemVariantForm, extra=5)

    # Handle form data
    if request.method == 'POST':
        if not request.user.has_perm('store.add_storeitem'):
            raise Http403

        item_form = StoreItemForm(request.POST, request.FILES)
        variant_formset = StoreItemFormSet(request.POST, prefix="nested", instance=item_form.instance)
        if item_form.is_valid() and variant_formset.is_valid():
            item = item_form.save()
            variant_formset.save()
            logger.info('Store Item "{}" added.'.format(item.name), extra={'user': request.user})
            return HttpResponseRedirect(reverse('manage-store:items'))
    else:
        item_form = StoreItemForm()
        variant_formset = StoreItemFormSet(prefix="nested", instance=item_form.instance)

    # Get items
    m_items = StoreItem.objects.all()

    # Render response
    return admin_render(request, "admin_store/items.html", {
        'items': m_items,
        'item_form': item_form,
        'variant_formset': variant_formset
    })
Exemple #13
0
def edit_item(request, item_id):
    if not request.user.has_perm('store.change_storeitem'):
        raise Http403

    StoreItemFormSet = inlineformset_factory(
        parent_model=StoreItem, model=StoreItemVariant, form=StoreItemVariantForm, extra=3)

    # Get Item
    item = get_object_or_404(StoreItem, pk=item_id)
        
    # Handle form data
    if request.method == 'POST':
        variant_formset = StoreItemFormSet(request.POST, instance=item)
        item_form = StoreItemForm(request.POST, request.FILES, instance=item)
        if item_form.is_valid() and variant_formset.is_valid():
            item_form.save()
            variant_formset.save()
            logger.info('Store Item "{}" edited.'.format(item.name), extra={'user': request.user})
            return HttpResponseRedirect(reverse('manage-store:edit_item', args=(item.id,)))
    else:
        item_form = StoreItemForm(instance=item)
        variant_formset = StoreItemFormSet(instance=item)

    # Render response
    return admin_render(request, "admin_store/itemedit.html", {
        'item_form': item_form,
        'variant_formset': variant_formset
    })
Exemple #14
0
def sentence_review(request):
    words = Words.objects.filter(jlpt_level = 5, id__lte=400)
    form_objects = []
    for word in words:
        full_form = type('', (), {})()

        word_form = WordsForm(instance=word)
        word_form.id = word.id
        full_form.word_form = word_form

        meaningset = inlineformset_factory(Words, WordMeanings, fields=('meaning',), form=MeaningsForm)
        meaningset = meaningset(instance=word)
        full_form.meaningset = meaningset 
        
        sentence_formset = modelformset_factory(Sentence, form=SentenceForm)
        no_sentence_owner_object = SentenceOwner.objects.get(name=" ")
        sentence_ids = Sentence.objects.filter(words=word).exclude(sentence_owner=no_sentence_owner_object).values_list('id', flat=True)[:5]
        sentence_query = Sentence.objects.filter(id__in=sentence_ids)
        sentence_formset = sentence_formset(queryset=sentence_query)
        full_form.sentence_formset = sentence_formset 

        form_objects.append(full_form)
        # sentence_formset = modelformset_factory(Sentence, form=SentenceForm)
    # return render(request, 'admin_data_collection/word_def_sentence_review.html', {"forms":form_objects, "word_form": word_form, "meanings_form": meaningset, "sentence_formset": sentence_formset} ) 
    return render(request, 'admin_data_collection/word_def_sentence_review.html', {"forms":form_objects}) 
Exemple #15
0
def edit_project(request, id):
    project = get_object_or_404(Project, pk=id)

    if request.user == project.created_by or request.user.is_superuser:
        RewardTierFormSet = inlineformset_factory(
            parent_model=Project,
            model=RewardTier,
            fields=('minimum_amount', 'description'),
            extra=0,
            can_delete=project.is_draft,
        )
        if request.method == 'POST':
            form = ProjectForm(request.POST, files=request.FILES, instance=project)
            reward_tier_formset = RewardTierFormSet(request.POST, instance=project)
            if form.is_valid() and reward_tier_formset.is_valid():
                publish = request.POST.get('publish', None)
                if project.status == Project.STATUS_DRAFT and publish == '1':
                    form.instance.publish()
                form.save()
                reward_tier_formset.save()
        else:
            form = ProjectForm(instance=project)
            reward_tier_formset = RewardTierFormSet(instance=project)

        return render(request, 'app/project/edit.html', context={
            'form': form,
            'reward_tier_formset': reward_tier_formset,
            'project': project,
        })
    else:
        raise PermissionDenied()
Exemple #16
0
def create_auction(request):
    AIFormSet = inlineformset_factory(Auction, AuctionedItem, form=AuctionedItemForm, can_delete=False, extra=1)
    if request.method == "POST":
        form = CreateAuctionForm(request.POST)
        formset = AIFormSet(request.POST)
        if form.is_valid() and formset.is_valid():
            try:
                data = form.cleaned_data
                data['auctioneditems'] = formset.cleaned_data
                auction = WhiteAuction.create(request.team, data)
                messages.add_message(request, messages.SUCCESS, "Aukce byla vytvořena.")
                Status.add("Tým %s právě vystavil aukci!" % request.team.name, Status.SUCCESS)
                return redirect(reverse("detail", args=(auction.id,)))
            except InvalidTransaction as e:
                form.add_error(None, str(e))
    else:
        form = CreateAuctionForm()
        formset = AIFormSet()

    return render(request, "auctions/create_auction.html", {
        'form': form,
        'items': formset,
        'empty_item': formset.empty_form,
        'balance': request.team.balance_set.all(),
    })
 def get_context_data(self, **kwargs):
     context = super(StockAdjustmentFormMixin, self).get_context_data(**kwargs)
     formset = inlineformset_factory(StockAdjustment, Stock, exclude=['adjustment'], extra=1)
     if hasattr(self, 'object'):
         context['formset'] = formset(instance=self.object)
     else:
         context['formset'] = formset(instance=None)
     return context
    def get_formset(self, request, obj, **kwargs):

        customer_notes = inlineformset_factory(Customer, Note, extra=0,
        formset=NoteInlineFormSet,
        fields=('title', 'details',))

        customer_notes.request = request
        return customer_notes
 def get_context_data(self, **kwargs):
     context = super(InvoiceFormMixin, self).get_context_data(**kwargs)
     formset = inlineformset_factory(Invoice, InvoiceLine, exclude=['invoice'], extra=1)
     if hasattr(self, 'object'):
         context['formset'] = formset(instance=self.object)
     else:
         context['formset'] = formset(instance=None)
     return context
Exemple #20
0
 def get(self, request, *args, **kwargs):
     self.DetalleFormSet = inlineformset_factory(Appoint, AppointDetail,form=AppointDetailForm, extra=0,
         fields=('tipo', 'trabajador', 'especialidad', 'cuadrilla', 'asignacion', 'nombrada'), min_num=1)
     self.object = self.get_object()
     self.appoint = Appoint.objects.get(pk=self.object.id)
     self.appointform = AppointForm(
         auto_id='appoint_%s', instance=self.appoint)
     return self.render_to_response(self.get_context_data())
 def get_context_data(self, **kwargs):
     context = super(PurchaseOrderFormMixin, self).get_context_data(**kwargs)
     formset = inlineformset_factory(PurchaseOrder, PurchaseOrderLine, exclude=['purchase_order'], extra=1)
     if hasattr(self, 'object'):
         context['formset'] = formset(instance=self.object)
     else:
         context['formset'] = formset(instance=None)
     return context
Exemple #22
0
 def get_context_data(self, **kwargs):
     context = super(QuestionDetail, self).get_context_data(**kwargs)
     question_id=context['question_object'].id
     # ChoiceFormSet=inlineformset_factory(Question,Choice,fields=('choice_text',),extra=0,widgets={"choice_text":Select()})
     ChoiceFormSet=inlineformset_factory(Question,Choice,fields=('choice_text',),extra=0)
     question=Question.objects.get(pk=question_id)
     choice_formset=ChoiceFormSet(instance=question)
     context['choice_formset'] = choice_formset
     return context
Exemple #23
0
def create(request):
    #render a template
    print("got to create")
    return render(request, "polls/create.html",{
        "form":QuestionForm(),
        "form1":forms.inlineformset_factory(
            Question, Choice,
            fields=('choice_text',))
})
 def get_context_data(self, **kwargs):
     context = super(ServiceFormMixin, self).get_context_data(**kwargs)
     context['customer'] = get_object_or_404(User, pk=self.kwargs.get('user_pk'))
     formset = inlineformset_factory(ServiceRequest, ServiceLine, exclude=['service'], extra=1)
     if hasattr(self, 'object'):
         context['formset'] = formset(instance=self.object)
     else:
         context['formset'] = formset(instance=None)
     return context
 def setUp(self):
     super(CsvGeneratorColumnFormSetTestCase, self).setUp()
     self.formset = forms.inlineformset_factory(
         CsvGenerator,
         CsvGeneratorColumn,
         formset=CsvGeneratorColumnFormSet,
         form=CsvGeneratorColumnForm,
         exclude=()
     )
Exemple #26
0
def item_new(request):

    ItemPhotoFormSet = inlineformset_factory(Item, ItemPhoto, fields=('image',), can_delete=False, extra=8)

    if request.method == "GET":

        initial_data = {
            'category': Category.objects.get(name="판매"),
            'state':'sale',
            'vendor': request.user,
            'name': strftime("%m-%d %H:%M:%S의 테스트 아이템"),
            'purchased_at': "최근",
            'shipping_price': "3000",
            'desc': "이것은 설명입니다.",
            'deal_place': "우리집",
            'deal_way': "direct",
            'condition': "S"
        }

        item_form = ItemForm(initial=initial_data)
        item = Item()
        item_photo_formset = ItemPhotoFormSet(instance=item)

    if request.method == "POST":
        item_form = ItemForm(data=request.POST)
        item = Item()
        item_photo_formset = ItemPhotoFormSet(instance=item)

        if item_form.is_valid():

            new_item = item_form.save(commit=False)
            new_item.vendor = request.user

            item_photo_formset = ItemPhotoFormSet(request.POST, request.FILES, instance = new_item)

            if item_photo_formset.is_valid():
                new_item.save()
                item_photo_formset.save()

                return redirect(new_item.get_absolute_url())

            else:
                print(item_photo_formset.errors)

        else:
            print("item_form is_valid is not true")
            print(item_form.errors)

    context = {
        'item_form': item_form,
        'item_photo_formset': item_photo_formset,
        'user': request.user,
        'title': '물품등록'
    }

    return render(request, 'shop/item_form.html', context)
def _create_site_rmc(request):
    """
    Create site for RMC account
    """
    rmc = Sesh_RMC_Account(api_key=rmc_tools.generate_rmc_api_key())
    rmc.save()
    site_forms_factory = inlineformset_factory(Sesh_RMC_Account, Sesh_Site, form=SiteRMCForm,exclude=('delete',))
    # Create RMC account associated with it
    form = site_forms_factory(request.POST, instance=rmc)
    return form
Exemple #28
0
	def get_formset_factory(cls):
		return inlineformset_factory(
			Poll,
			Choice,
			form=ChoiceForm,
			extra=1,
			can_delete=True,
			min_num=2,
			validate_min=True,
			formset=AtLeastNFormSet,
		)
Exemple #29
0
 def get_context_data(self, **kwargs):
     """ Adds submission file upload formsets to context. """
     context = super(AccountAuthorView, self).get_context_data(**kwargs)
     file_upload_form = AuthorFileForm if Conference.objects.active_conference().is_file_upload_enabled else AuthorFileFormReadOnly
     factory = inlineformset_factory(AuthorProfile, Submission, extra=0, can_delete='False', form=file_upload_form)
     context['file_formset'] = factory(self.request.POST or None, self.request.FILES or None, instance=self.request.user.authorprofile,
                                       queryset=Submission.objects.accepted().active())
     context['not_accepted_submissions'] = Submission.objects.not_accepted().active().filter_by_author(self.request.user)
     context['denied_submissions'] = Submission.objects.denied().active().filter_by_author(self.request.user)
     context['coauthor_submissions'] = Submission.objects.active().filter_by_coauthor(self.request.user)
     return context
    def get_formset(self, request, obj, **kwargs):

        reminder_formset = inlineformset_factory(Customer, Reminder,
            formset=ReminderInlineFormset,
            extra=0,
            form=ReminderInlineForm)

        reminder_formset.request = request
        reminder_formset.obj = obj

        return reminder_formset
Exemple #31
0
from django import forms
from django.forms import inlineformset_factory
from community.models import Village, School


class SchoolAddForm(forms.ModelForm):
    class Meta:
        model = School
        fields = [
                    'village',
                    'name',
                    'description',
                ]
        help_texts = {
                'name': '<--School where you studied & want to be part of!',
                'village': '<--Village where this school is!',
        }


class VillageAddForm(forms.ModelForm):
    class Meta:
        model = Village
        fields = [
                    'name',
                    'district',
                    'description',
                ]
SchoolAddFormSet = inlineformset_factory(Village, School, fields=('name', 'description',), extra=1, can_delete=False)
Exemple #32
0
            'class': 'form-control mypricefield'
        })
        # self.fields['producto'].widget.attrs['required'] = True
        self.fields['cantidad'].widget.attrs['min'] = 1
        self.fields['cantidad'].widget.attrs['required'] = True
        self.fields['precio'].widget.attrs['min'] = 1
        self.fields['precio'].widget.attrs['readonly'] = True

    class Meta:
        model = DetallePedido
        exclude = ()


DetallePedidoFormSet = inlineformset_factory(Pedido,
                                             DetallePedido,
                                             form=DetallePedidoForm,
                                             extra=1,
                                             can_delete=True)

# ------------------------------------


class VentaForm(ModelForm):
    pedido = forms.ModelChoiceField(
        queryset=Pedido.objects.all(),
        empty_label="Seleccione el Numero del Pedido a Cancelar")
    fecha = forms.DateTimeField(initial=datetime.datetime.now,
                                widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super(VentaForm, self).__init__(*args, **kwargs)
Exemple #33
0
from django.contrib.auth.decorators import login_required
from django.core import exceptions
from django.core.paginator import Paginator
from django.db.models import Count, Q
from django.db.models.functions import Lower
from django.shortcuts import render, get_object_or_404, redirect
from django.template.defaulttags import register
from taggit.models import Tag

import CE.forms
import CE.utilities
from CE import OCM_categories
from CE.models import CultureEvent, Text, Picture, Visit, Question

text_form_factory = forms.inlineformset_factory(CE.models.CultureEvent,
                                                CE.models.Text,
                                                form=CE.forms.TextForm,
                                                extra=0)

question_form_factory = forms.inlineformset_factory(CE.models.CultureEvent,
                                                    CE.models.Question,
                                                    form=CE.forms.QuestionForm,
                                                    extra=0)

visits_form_factory = forms.inlineformset_factory(CE.models.CultureEvent,
                                                  CE.models.Visit,
                                                  form=CE.forms.VisitsForm,
                                                  extra=0)


@CE.utilities.conditional_login
def home_page(request):
Exemple #34
0
        model = Post
        fields = [
            'content',
        ]


class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = [
            'file',
        ]


ImageFormSet = forms.inlineformset_factory(Post,
                                           Image,
                                           form=ImageForm,
                                           extra=3)


class CommentForm(forms.ModelForm):
    content = forms.CharField(
        label='',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '댓글을 작성하세요'
        }))

    class Meta:
        model = Comment
        fields = [
            'content',
Exemple #35
0
        widgets = {
            'symptom': forms.HiddenInput(),
            'label': forms.HiddenInput(),
            'onset': forms.DateInput(format='%Y-%m-%d', attrs={'type':
                                                               'date'}),
            'intensity': forms.HiddenInput()
        }

    label = forms.CharField(widget=forms.HiddenInput(),
                            required=False,
                            empty_value='')


SymptomInlineFormset = inlineformset_factory(models.Monitoring,
                                             model=models.Symptom,
                                             form=SymptomCreateForm,
                                             extra=len(choices.symptoms),
                                             can_delete=False)


class TripForm(forms.ModelForm):
    class Meta:
        model = models.Trip
        fields = '__all__'
        widgets = {
            'profile':
            forms.HiddenInput(),
            'departure_date':
            forms.DateInput(format='%d/%m/%Y', attrs={'type': 'date'}),
            'return_date':
            forms.DateInput(format='%d/%m/%Y', attrs={'type': 'date'}),
Exemple #36
0
from django.forms import ModelForm, inlineformset_factory

from .models import Profile, FamilyMember


class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        exclude = ()


class FamilyMemberForm(ModelForm):
    class Meta:
        model = FamilyMember
        exclude = ()


FamilyMemberFormSet = inlineformset_factory(Profile,
                                            FamilyMember,
                                            form=FamilyMemberForm,
                                            extra=1)
Exemple #37
0
            'DescripItem': 'Descripción',
            'UnidItem': 'Unidad',
            'CantItem': 'Cantidad',
            'PuItem': 'Precio Unitario',
            'TotalItem': 'Total',
            'ObservItem': 'Obs'
        }

    def __init__(self, *args, **kwargs):
        super(ItemOdcForm, self).__init__(*args, **kwargs)
        self.fields['NumItem'].widget.attrs['style'] = "width:150px"
        self.fields['IdCecoODC'].widget.attrs['style'] = "width:300px"
        self.fields['DescripItem'].widget.attrs['style'] = "width:800px"


ItemOdcFormSet = inlineformset_factory(Odc, ItemOdc, form=ItemOdcForm, extra=1)


class ItemCttoForm(forms.ModelForm):
    class Meta:
        model = ItemCtto
        fields = [
            'NumItem', 'IdCecoCtto', 'PresupuestoItem', 'ItemCodBudget',
            'DescripItem', 'UnidItem', 'CantItem', 'PuItem', 'TotalItem',
            'ObservItem'
        ]
        exclude = ()
        labels = {
            'NumItem': 'Item',
            'IdCecoCtto': 'Cuenta',
            'PresupuestoItem': 'Presupuesto',
Exemple #38
0
                    'class': 'form-control',
                }
            ),
            'name': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
        }


AboutGalleryFormset = forms.inlineformset_factory(
    AboutPage,
    AboutGallery,
    AboutGalleryForm,
    fields=('image',),
    extra=1,
    max_num=5,
    min_num=1,
)
AboutExtraInfoFormset = forms.inlineformset_factory(
    AboutPage,
    AboutExtraInfo,
    AboutExtraInfoForm,
    fields=(
        'title',
        'short_text',
    ),
    extra=0,
    max_num=1,
    min_num=1,
Exemple #39
0
                                 widget=SelectDateWidget())
    end_date = forms.DateField(required=False,
                               label=_("End Date"),
                               widget=SelectDateWidget())

    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')

        if end_date and end_date < start_date:
            self.add_error('end_date',
                           _('End Date cannot be before Start Date'))
            del (cleaned_data['end_date'])

        return cleaned_data


##########
# From Sets
##########

PriceFormSet = inlineformset_factory(Offer,
                                     Price,
                                     form=PriceForm,
                                     can_delete=False,
                                     exclude=('offer', ),
                                     validate_max=True,
                                     min_num=1,
                                     extra=0)
Exemple #40
0
def AddQuiz(request):
    QuestionFormset = inlineformset_factory(Quiz,
                                            Question,
                                            fields=['text'],
                                            extra=1,
                                            can_delete=False)
    AnswerFormset = inlineformset_factory(Question,
                                          Answer,
                                          fields=['text', 'correct'],
                                          extra=4,
                                          can_delete=False)
    # QuizForm(initial={'time':5, 'required_score_to_pass': 1, 'difficulty': 'medium'})
    question_form = QuestionFormset()
    answer_form = AnswerFormset()
    if request.method == 'POST':
        quiz_form = QuizForm(request.POST,
                             initial={
                                 'time': 5,
                                 'required_score_to_pass': 1,
                                 'difficulty': 'medium',
                                 'topic': 'test quiz'
                             })
        if quiz_form.is_valid() and quiz_form.has_changed():
            quiz_form.instance.user = request.user
            quiz_instance = quiz_form.save().id
            quiz_id = quiz_instance
            quiz_instance = Quiz.objects.get(pk=quiz_instance)
            question_form = QuestionFormset(request.POST,
                                            instance=quiz_instance)
            if question_form.is_valid() and question_form.has_changed():
                Question_instance = question_form[0].instance
                answer_form = AnswerFormset(request.POST,
                                            instance=Question_instance)
                if answer_form.is_valid() and answer_form.has_changed(
                ) and len(answer_form) > 0:
                    question_form.save()
                    answer_form.save()
                    messages.success(request, f'Question saved successfully!')
                    if 'create_quiz_save_btn' in request.POST:
                        return redirect('quiz-home')
                    else:
                        return redirect('add_more_question', quiz_id)
                else:
                    messages.info(request, f'Fill option!')
            else:
                messages.info(request, f'Fill question details')
        else:
            messages.info(
                request,
                f"Please fill all '*' marked fields while entering Quiz details"
            )

    else:
        quiz_form = QuizForm(
            initial={
                'time': 5,
                'required_score_to_pass': 1,
                'difficulty': 'medium',
                'topic': 'test quiz'
            })
        question_form = QuestionFormset()
        answer_form = AnswerFormset()

    context = {
        'quiz_form': quiz_form,
        'question_form': question_form,
        'answer_form': answer_form,
    }

    return render(request, 'quiz/quiz_create.html', context)
Exemple #41
0
from django import forms
from .models import WorkHour, Moderator


class WorkHourForm(forms.ModelForm):
    """Work Hours Form."""
    class Meta:
        model = WorkHour
        fields = ['day', 'hour', 'duration']
        labels = {
            'day': 'Dia',
            'hour': 'Hora',
            'duration': 'Duração',
        }


WorkHourFormSet = forms.inlineformset_factory(Moderator,
                                              WorkHour,
                                              form=WorkHourForm,
                                              can_delete=True,
                                              extra=1,
                                              max_num=1000)
        fields = [
            'employee_or_student_id',
            'requested_role',
            'email',
            'approval_extra_note']


class ApprovalProfileUpdateForm(djform.ModelForm):
    class Meta:
        model = User
        fields = ['requested_role']


UserProfileSocialLinksFormSet = inlineformset_factory(
    CommonUserProfile, SocialLink,
    fields=('media_name', 'url'),
    extra=4,
    max_num=4
)

class CommonUserProfileForm(djform.ModelForm):
    class Meta:
        model = CommonUserProfile
        fields = [
            'profile_picture',
            'cover_picture',
            'headline',
            'show_headline_in_bio',
            'country',
            'summary'
        ]
Exemple #43
0
            'max_width', 0) if self.cleaned_data.get('max_width') else 0
        max_h = self.cleaned_data.get(
            'max_height', 0) if self.cleaned_data.get('max_height', 0) else 0
        if commit:
            # If committing, save the instance and the m2m data immediately.
            self._save_m2m()
            #raise commit
        else:
            # If not committing, add a method to the form to allow deferred
            # saving of m2m data.
            self.save_m2m = self._save_m2m
        self.instance.save(max_width=max_w, max_height=max_h)
        return self.instance


ImageFormSet = forms.inlineformset_factory(Offers, Images, ImageForm)


class PriceForm(FormAjaxBase):
    class Meta:
        model = Price
        fields = (
            'price_type',
            'value',
        )

    def get_context(self):
        return {'price_types': PriceType.objects.all()}

    def save_to_database(self, request):
        model_id = request.POST.get('model-id', None)
Exemple #44
0
        model = TestCaseEmailSettings
        fields = "__all__"

    cc_list = MultipleEmailField(required=False)


# note: these fields can't change during runtime !
_email_settings_fields = []  # pylint: disable=invalid-name
for field in TestCaseEmailSettings._meta.fields:
    _email_settings_fields.append(field.name)

# for usage in CreateView, UpdateView
CaseNotifyFormSet = inlineformset_factory(  # pylint: disable=invalid-name
    TestCase,
    TestCaseEmailSettings,
    form=CaseNotifyForm,
    fields=_email_settings_fields,
    can_delete=False,
    can_order=False,
)


# TODO: search page can search via text field which is not defined here
# this will become important once we switch to ModelForm and make
# the search page remember it's URL params to it can be bookmarked
class BaseCaseSearchForm(forms.Form):
    summary = forms.CharField(required=False)
    author = forms.CharField(required=False)
    default_tester = forms.CharField(required=False)
    tag__name__in = forms.CharField(required=False)
    category = forms.ModelChoiceField(queryset=Category.objects.none(),
                                      required=False)
Exemple #45
0
class GraphFrom(forms.Form):
    try:
        choices = Components_Type.objects.all()
        comptype = forms.ChoiceField(choices=choices.values_list())
        x_axis = forms.ChoiceField()
        x_log_scale = forms.BooleanField(required=False)
        y_axis = forms.ChoiceField()
        y_log_scale = forms.BooleanField(required=False)
    except ProgrammingError:
        pass

    def __init__(self, *args, **kwargs):
        self.type_id = kwargs.pop('type_id')
        super().__init__(*args, **kwargs)

        choices = Key_Param.objects.all().values_list('pk', 'name_text')
        self.fields['y_axis'] = forms.ChoiceField(choices=choices)
        self.fields['x_axis'] = forms.ChoiceField(choices=choices)


PerfInline = forms.inlineformset_factory(Component,
                                         Key_Perf,
                                         fields=('key_param', 'value'))


class ComponentForm(forms.ModelForm):
    class Meta:
        model = Component
        exclude = ('perf_record', )
Exemple #46
0
import logging
from django import forms
from django.forms import inlineformset_factory
from django_countries.widgets import CountrySelectWidget
from . import models
from .tasks import contact_us_form_filled

logger = logging.getLogger(__name__)

CartLineFormSet = inlineformset_factory(
    models.Cart,
    models.CartLine,
    fields=("quantity", ),
    extra=0,
)


class ContactUsForm(forms.Form):
    name = forms.CharField(label='Your name', max_length=100)
    message = forms.CharField(max_length=600, widget=forms.Textarea)

    def send_mail(self):
        logger.info("Sending email to customer service")
        contact_us_form_filled.delay(self.cleaned_data)


class AddressForm(forms.ModelForm):
    use_default = forms.BooleanField(initial=False, required=False)

    class Meta:
        model = models.Address
Exemple #47
0
    model = Options
    fields = '__all__'

class CreateOrderView(UpdateWithInlinesView):
    model = Questions
    inlines = [OptionsInline,]
    fields = '__all__'
    template_name = 'exams/updatequest.html'
    success_url = '/'
    factory_kwargs = {'extra': 0}



from django.views.generic import TemplateView, ListView, CreateView

QuestionsInlineFormSet = inlineformset_factory(Exam, Questions,fields='__all__', extra=1, can_delete=False)
OptionsInlineFormSet = inlineformset_factory(Questions, Options,fields='__all__', extra=1, can_delete=False)


class ExamCreateView(CreateView):
    model = Exam
    fields='__all__'
    template_name = 'exams/tem.html'
    factory_kwargs = {'extra': 0}
    success_url = '/'

    def form_valid(self, form):
        result = super(ExamCreateView, self).form_valid(form)

        questions_formset = QuestionsInlineFormSet(form.data, instance=self.object, prefix='questions_formset')
        if questions_formset.is_valid():
Exemple #48
0
		data = self.cleaned_data["city"]
		if data is not None:
			data = data.capitalize()
		return data

class BuyableForm(forms.ModelForm):
	class Meta:
		model = Buyable
		fields = [
			'buyable_name',
			'price',
			'tax_rate',
		]
		
BuyableFormSet = formset_factory(BuyableForm, extra=5, max_num=5)
BuyableInlineFormSet = inlineformset_factory(Event, Buyable, form=BuyableForm, extra=5, max_num = 5)
BuyableModelFormSet = modelformset_factory(Buyable, form=BuyableForm, extra=5, max_num = 5)

def validate_with_initial(formset):
	valid = True
	for form in formset:
		if form.has_changed():
			if not form.is_valid():
				valid = False
				print('INVALID')
	return valid

class EventForm(forms.ModelForm):
	class Meta:
		model = Event
		fields = [
Exemple #49
0
        fields = '__all__'
        exclude = ['user']


class UserForm(ModelForm):
    class Meta:
        model = get_user_model()
        fields = ['username', 'email']
        exclude = ['user']


CartLineFormSet = inlineformset_factory(
    Cart,
    CartLine,

    fields=('quantity',),
    extra=0,
    widgets={'quantity': widgets.PlusMinusInput()}

)


class AddressSelectionForm(forms.Form):
    billing_address = forms.ModelChoiceField(
        queryset=None)
    shipping_address = forms.ModelChoiceField(
        queryset=None)

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        queryset = models.Address.objects.filter(user=user)
Exemple #50
0
    def save(self):
        template = super(CertificateTemplateForm, self).save()
        if self.cleaned_data['is_approved']:
            certificate_request = template.certificate_request
            certificate_request.is_approved = True
            certificate_request.save()
            for user in template.certificate_request.users.all():
                certificate = template.generate_certificate(user, user.common_profile.get_en_full_name())

        return template

    class Meta:
        model = CertificateTemplate
        fields = ['example_text', 'description', 'image',
                  'image_format']

class VerifyCertificateForm(forms.Form):
    verification_code = forms.CharField(max_length=6, min_length=6,
                                        label=u"رمز التحقق")

PositionFormset =  inlineformset_factory(CertificateTemplate, TextPosition,
                                         fields=('y_position', 'y_center',
                                                 'x_position','x_center',
                                                 'font_family',
                                                 'size', 'color'),
                                         widgets={'color': forms.TextInput(attrs={'class': 'jscolor english-field'})})

class CertificateForm(forms.ModelForm):
    class Meta(UserAutocompleteFormMeta):
        model = Certificate
Exemple #51
0
        fields = ['amount_sent']

    def __init__(self, *args, **kwargs):
        super(SRForm, self).__init__(*args, **kwargs)
        curmax = int(kwargs['instance'].sender.participant.vars['herd_size'])
        self.fields['amount_sent'] = forms.IntegerField(label='How many cattle will you send this player?',
                                                        required=True,
                                                        max_value=curmax,
                                                        min_value=0,
                                                        )


class BaseSRFormset(BaseInlineFormSet):
    def clean(self):
        if any(self.errors):
            return
        tot_amount_sent = 0
        for form in self.forms:
            tot_amount_sent += form.cleaned_data['amount_sent']
        max_sent = int(self.instance.participant.vars['herd_size'])
        if tot_amount_sent > max_sent:
            raise forms.ValidationError("The maximum amount you can send is {}".format(max_sent))


SRFormSet = inlineformset_factory(Player, SendReceive,
                                  fk_name='sender',
                                  can_delete=False,
                                  extra=0,
                                  form=SRForm,
                                  formset=BaseSRFormset)
Exemple #52
0
    step_num_param = forms.IntegerField(initial=1,
                                        required=False,
                                        label='Tamanho do passo')

    cons_misses = forms.IntegerField(
        initial=100,
        required=False,
        label=('Falhas consecutivas necessárias para considerar um intervalo '
               'do parâmetro inválido'))


# Formset for ResponseHandler forms
ResponseHandlerFormSet = forms.inlineformset_factory(CrawlRequest,
                                                     ResponseHandler,
                                                     form=ResponseHandlerForm,
                                                     exclude=[],
                                                     extra=0,
                                                     min_num=0,
                                                     can_delete=True)

# Formset for ParameterHandler forms
ParameterHandlerFormSet = forms.inlineformset_factory(
    CrawlRequest,
    ParameterHandler,
    form=ParameterHandlerForm,
    exclude=[],
    extra=0,
    min_num=0,
    can_delete=True)
Exemple #53
0
class SpecialistContactForm(forms.ModelForm):
    phone = PhoneNumberField(
        required=False,
        widget=forms.TextInput(attrs={'placeholder': _('Номер телефона')}))

    class Meta:
        model = SpecialistContact
        fields = [
            'phone',
        ]


ContactFormSet = forms.inlineformset_factory(Specialist,
                                             SpecialistContact,
                                             form=SpecialistContactForm,
                                             extra=1,
                                             can_delete=True)


class CompanyCreateForm(forms.ModelForm):
    name = forms.CharField(
        required=True,
        widget=forms.TextInput(
            attrs={'placeholder': _('Название учреждения')}))
    email = forms.EmailField(
        required=False,
        widget=forms.EmailInput(
            attrs={'placeholder': _('Эл. адрес компании')}))
    website = forms.URLField(
        required=False,
            self.user = authenticate(self.request,
                                     email=email,
                                     password=password)
        if self.user is None:
            raise forms.ValidationError("Invalid email/password combination.")
        logger.info("Authentication successful for email=%s", email)
        return self.cleaned_data

    def get_user(self):
        return self.user


BasketLineFormSet = inlineformset_factory(
    models.Basket,
    models.BasketLine,
    fields=("quantity", ),
    extra=0,
    widgets={"quantity": widgets.PlusMinusNumberInput()},
)


class AddressSelectionForm(forms.Form):
    billing_address = forms.ModelChoiceField(queryset=None)
    shipping_address = forms.ModelChoiceField(queryset=None)

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        queryset = models.Address.objects.filter(user=user)
        self.fields['billing_address'].queryset = queryset
        self.fields['shipping_address'].queryset = queryset
Exemple #55
0
def project_edit_new(request,pk):
    mission_edit_details = inlineformset_factory(Project,ProjectMission, extra=0,can_delete=False, form=ProjectMissionFormset)
    proj_comm_part_edit = inlineformset_factory(Project,ProjectCommunityPartner, extra=0, can_delete=False, form=AddProjectCommunityPartnerForm)
    proj_campus_part_edit = inlineformset_factory(Project,ProjectCampusPartner, extra=0, can_delete=False,  form=AddProjectCampusPartnerForm)
    print('print input to edit')
    if request.method == 'POST':
        proj_edit = Project.objects.filter(id=pk)
        for x in proj_edit:
            project = ProjectForm2(request.POST or None, instance=x)
            course = CourseForm(request.POST or None, instance=x)

        formset_missiondetails = mission_edit_details(request.POST ,request.FILES, instance =x)
        formset_comm_details = proj_comm_part_edit(request.POST, request.FILES, instance=x)
        formset_camp_details = proj_campus_part_edit(request.POST, request.FILES, instance=x)
        print("before form validations", formset_camp_details.is_valid(), formset_comm_details.is_valid(),project.is_valid(), course.is_valid())
        # print("formset_missiondetails.is_valid()8888888888", formset_missiondetails.is_valid())
        if project.is_valid() and formset_camp_details.is_valid() and formset_comm_details.is_valid():
                #print(" validating the forms here")
                instances = project.save()
                # print(instances.engagement_type)
                # eng = str(project.engagement_type)
                # if project.engagement_type == "Service Learning":
                #     print("heoooooooooooooooooo")
                #     course = course.save(commit=False)
                #     course.project_name = project
                #     course.save()
                pm = formset_missiondetails.save(commit=False)
                compar= formset_comm_details.save(commit=False)
                campar= formset_camp_details.save(commit=False)

                for k in pm:
                    k.project_name = instances
                    k.save()
                for p in compar:
                    p.project_name= instances
                    p.save()
                for l in campar:
                    l.project_name= instances
                    l.save()
                projects_list = []
                camp_part_names = []
                course_list = []
                # Get the campus partner id related to the user
                camp_part_user = CampusPartnerUser.objects.filter(user_id=request.user.id)
                for c in camp_part_user:
                    p = c.campus_partner_id
                    # print(c)
                # get all the project names base on the campus partner id
                proj_camp = list(ProjectCampusPartner.objects.filter(campus_partner_id=p))
                for f in proj_camp:
                    k = list(Project.objects.filter(id=f.project_name_id))
                    # print(k)
                    tot_hours = 0
                    for x in k:

                        projmisn = list(ProjectMission.objects.filter(project_name_id=x.id))
                        cp = list(ProjectCommunityPartner.objects.filter(project_name_id=x.id))
                        proj_camp_par = list(ProjectCampusPartner.objects.filter(project_name_id=x.id))
                        for proj_camp_par in proj_camp_par:
                            camp_part = CampusPartner.objects.get(id=proj_camp_par.campus_partner_id)
                            tot_hours += proj_camp_par.total_hours * proj_camp_par.total_people
                            # total_project_hours += proj_camp_par.total_hours
                            x.total_uno_hours = tot_hours
                            print("total hours", tot_hours)
                            x.total_uno_students += proj_camp_par.total_people
                            print("total students", x.total_uno_students)
                            x.save()
                            camp_part_names.append(camp_part)
                        list_camp_part_names = camp_part_names
                        camp_part_names = []

                        data = {'pk': x.pk, 'name': x.project_name, 'engagementType': x.engagement_type,
                                'activityType': x.activity_type, 'academic_year': x.academic_year,
                                'facilitator': x.facilitator, 'semester': x.semester, 'status': x.status,'description':x.description,
                                'startDate': x.start_date,
                                'endDate': x.end_date, 'total_uno_students': x.total_uno_students,
                                'total_uno_hours': x.total_uno_hours,
                                'total_k12_students': x.total_k12_students, 'total_k12_hours': x.total_k12_hours,
                                'total_uno_faculty': x.total_uno_faculty,
                                'total_other_community_members': x.total_other_community_members, 'outcomes': x.outcomes,
                                'total_economic_impact': x.total_economic_impact, 'projmisn': projmisn, 'cp': cp,
                                'camp_part': list_camp_part_names,



                                }

                        projects_list.append(data)


                return render(request, 'projects/Projectlist.html', {'project': projects_list})

    else:
            #print(" Project_edit_new else")
            proj_edit = Project.objects.filter(id=pk)

            for x in proj_edit:
                project = ProjectForm2(request.POST or None, instance=x)


            # coursedetail = Course.objects.filter(project_name_id=pk)
            course = CourseForm(instance = x)
            # print(course)
            proj_mission = ProjectMission.objects.filter(project_name_id=pk)
            proj_comm_part = ProjectCommunityPartner.objects.filter(project_name_id = pk)
            proj_camp_part = ProjectCampusPartner.objects.filter(project_name_id = pk)
            # course_details = course(instance= x)
            formset_missiondetails = mission_edit_details(instance=x)
            formset_comm_details = proj_comm_part_edit(instance=x)
            formset_camp_details = proj_campus_part_edit(instance=x)
            print("formset_camp_details",formset_camp_details)
            return render(request,'projects/projectedit.html',{'project': project,'course': course,
                                                   'formset_missiondetails':formset_missiondetails,
                                                   'formset_comm_details': formset_comm_details,
                                                   'formset_camp_details':formset_camp_details})
Exemple #56
0
from django.forms import inlineformset_factory
from courses.models import Module, Course, Assignment

ModuleInlineFormset = inlineformset_factory(Course, Module, extra=2, 
                                            fields=['title', 'description'], can_delete=True)

AssignmentInlineFormset = inlineformset_factory(Course, Assignment, extra=2, 
                                                fields=['title', 'description', 'ifile'], can_delete=True)
Exemple #57
0
def get_asset_formset_class(form=forms.ModelForm,
                            formset=forms.BaseInlineFormSet,
                            **kwargs):
    return forms.inlineformset_factory(Page, Asset, form, formset, **kwargs)
Exemple #58
0
        })
        self.fields['apellidos'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': 'Apellidos'
        })
        self.fields['documento_identidad'].widget.attrs.update({
            'class':
            'form-control',
            'placeholder':
            'Documento de Identidad'
        })


campos = (
    'fk_tipo_documento',
    'nombres',
    'apellidos',
    'documento_identidad',
)

FormsetObj = modelform_factory(Vocero, form=FormularioVocero, fields=campos)

FormsetVocero = inlineformset_factory(OrganizacionSocial,
                                      Vocero,
                                      form=FormsetObj,
                                      fields=campos,
                                      fk_name='fk_org_social',
                                      min_num=1,
                                      extra=0,
                                      validate_min=True,
                                      can_delete=True)
Exemple #59
0
def DashboardView(request):
    try:
        vendorprofile = get_object_or_404(models.vendorprofile,
                                          user=request.user)
        VendorBankFormset = inlineformset_factory(models.vendorprofile,
                                                  models.bank_detail,
                                                  exclude=['vendor'],
                                                  extra=0,
                                                  can_delete=False)
        if request.method == 'POST':
            type = request.POST['type']
            if type == 'profile':
                profile_form = forms.VendorProfileForm(request.POST,
                                                       request.FILES,
                                                       instance=vendorprofile)
                bank_formset = VendorBankFormset(request.POST,
                                                 request.FILES,
                                                 instance=vendorprofile)
                if profile_form.is_valid() and bank_formset.is_valid():
                    profile_form.save()
                    bank_formset.save()
                    messages.success(
                        request,
                        'Details Saved Successfully',
                        extra_tags='alert alert-success alert-dismissible')
                    return redirect('vendor:dashboard')
                else:
                    messages.success(
                        request,
                        'Please Update Details Correctly',
                        extra_tags='alert alert-danger alert-dismissible')
                    context = {
                        'profile_form': profile_form,
                        'bank_formset': bank_formset,
                        'vendor': vendorprofile,
                    }
                    return render(request, 'Vendor/profile.html', context)
            elif type == 'change_password':
                password = request.POST['current_password']
                new_password = request.POST['new_password']
                user = authenticate(username=request.user.username,
                                    password=password)
                if user is not None:
                    user.set_password(new_password)
                    user.save()
                    login(request, user)
                    messages.success(
                        request,
                        'Password Updated',
                        extra_tags='alert alert-success alert-dismissible')
                    return redirect('vendor:dashboard')
                else:
                    messages.error(
                        request,
                        'Invalid Password',
                        extra_tags='alert alert-error alert-dismissible')
        else:
            profile_form = forms.VendorProfileForm(instance=vendorprofile)
            bank_formset = VendorBankFormset(instance=vendorprofile)
            context = {
                'profile_form': profile_form,
                'bank_formset': bank_formset,
                'vendor': vendorprofile,
            }
            return render(request, 'Vendor/profile.html', context)
    except:
        return redirect('core:dashboard')
Exemple #60
0
def group_marks_edit(request, group_pk, discipline_pk):
    group = get_object_or_404(models.University_Group, pk=group_pk)

    group_discipline = get_object_or_404(models.DisciplineForGroup,
                                         pk=discipline_pk)
    group_marks = models.Mark.objects.all().filter(discipline=discipline_pk)

    group_marks_formset_model = inlineformset_factory(
        models.DisciplineForGroup,
        models.Mark,
        # fields=(
        #     'student', 'marks', 'type_of_mark', 'number_of_type_of_mark'),
        extra=0,
        can_delete=True,
        form=MarkForm,
    )

    old_numbers_of_works_info = get_dict_with_numbers_of_works_of_group_discipline(
        group_discipline=group_discipline)
    # works_info_for_table = {key: range(1, old_numbers_of_works_info[key] + 1) for key in
    #                         old_numbers_of_works_info.keys()}
    # print(works_info_for_table.items())
    works_info_for_table = []

    for key, value in old_numbers_of_works_info.items():
        if value > 0:
            if key == 'number_of_lectures':
                works_info_for_table.append(('Лекция', range(
                    1, value + 1), choices.matching_numbers_and_names[key]), )
            elif key == 'number_of_laboratory_lessons':
                works_info_for_table.append(
                    ('Лабораторная работа', range(1, value + 1),
                     choices.matching_numbers_and_names[key]), )
            elif key == 'number_of_practical_lessons':
                works_info_for_table.append(
                    ('Практическая работа', range(1, value + 1),
                     choices.matching_numbers_and_names[key]), )
            elif key == 'number_of_home_works':
                works_info_for_table.append(
                    ('Домашная работа', range(1, value + 1),
                     choices.matching_numbers_and_names[key]), )
            elif key == 'number_of_tests':
                works_info_for_table.append(('Тест', range(
                    1, value + 1), choices.matching_numbers_and_names[key]), )
            elif key == 'course_work':
                works_info_for_table.append(
                    ('Курсовая работа', None,
                     choices.matching_numbers_and_names[key]), )
    print(works_info_for_table)
    # for key, value in (
    #         ('number_of_lectures', LECTURE), ('number_of_practical_lessons', PRACTICAL_LESSON),
    #         ('number_of_laboratory_lessons', LABORATORY_LESSON), ('number_of_tests', TEST),
    #         ('number_of_home_works', HOME_WORK), ('course_work', COURSE_WORK)):
    #     matching_numbers_and_names[key] = value
    print('старое число работ: ', old_numbers_of_works_info)
    if request.method == "POST":
        discipline_form = DisciplineForGroupMarksForm(
            request.POST or None, instance=group_discipline)
        group_marks_formset = group_marks_formset_model(
            request.POST or None,
            instance=group_discipline,
            prefix='group_marks')

        # print(discipline_form.is_valid(), group_marks_formset.is_valid())
        if discipline_form.is_valid() and group_marks_formset.is_valid():
            # number_of_lectures = int(discipline_form.cleaned_data['number_of_lectures'])
            new_numbers_of_works_info = discipline_form.cleaned_data
            changed_values_of_works_info = dict([
                x for x in new_numbers_of_works_info.items()
                if x not in old_numbers_of_works_info.items()
            ])

            print('Новое число работ:', new_numbers_of_works_info)
            print('измененные значения', changed_values_of_works_info)
            print(
                '2 вариант пересечения: ',
                dict(old_numbers_of_works_info.items()
                     & new_numbers_of_works_info.items()))

            for key, value in changed_values_of_works_info.items():
                if value > old_numbers_of_works_info[key]:
                    for i in range(old_numbers_of_works_info[key] + 1,
                                   value + 1):
                        for student in group_discipline.group.student_group.all(
                        ):
                            new_mark = models.Mark(
                                discipline=group_discipline,
                                student=student,
                                type_of_mark=choices.
                                matching_numbers_and_names[key],
                                number_of_type_of_mark=i,
                                mark=0)
                            new_mark.save()
                elif value < old_numbers_of_works_info[key]:
                    for i in range(
                            value + 1,
                            old_numbers_of_works_info[key] + 1,
                    ):
                        for student in group_discipline.group.student_group.all(
                        ):
                            # new_mark = models.Mark(discipline=group_discipline, student=student,
                            #                        type_of_mark=choices.matching_numbers_and_names[key],
                            #                        number_of_type_of_mark=i, marks=0)
                            models.Mark.objects.filter(
                                discipline=group_discipline,
                                student=student,
                                type_of_mark=choices.
                                matching_numbers_and_names[key],
                                number_of_type_of_mark=i).delete()
                            # new_mark.save()
            # if group_discipline.number_of_lectures != number_of_lectures:
            #     for i in range(1, number_of_lectures + 1):
            #         for student in group_discipline.group.student_group.all():
            #             new_mark = models.Mark(discipline=group_discipline, student=student,
            #                                    type_of_mark=choices.LABORATORY_LESSON,
            #                                    number_of_type_of_mark=i, marks=0)
            #             new_mark.save()
            # print(new_mark)
            discipline_form.save()
            group_marks_formset.save()
            return redirect('group_detail',
                            group_pk=group_pk,
                            discipline_pk=discipline_pk)

    else:
        discipline_form = DisciplineForGroupMarksForm(
            instance=group_discipline)
        group_marks_formset = group_marks_formset_model(
            instance=group_discipline, prefix='group_marks')
    context = {
        'group': group,
        'group_marks': group_marks,
        # 'subject': subject,
        'group_discipline': group_discipline,
        'discipline_form': discipline_form,
        'group_marks_formset': group_marks_formset,
        'works_info_for_table': works_info_for_table,
    }
    # for form in group_marks_formset.forms:
    #     print(form.student)
    return render(request, 'NURE_marks/group_marks_edit.html', context)