Пример #1
0
def view_cf(request, cf_id):
    base_cf = CustomForm.objects.get(id=cf_id)
    surveytaker = request.session
    cf,c=CustomForm.objects.get_or_create(surveytaker=surveytaker,createdbyuser=base_cf.createdbyuser,name=base_cf.name)
    if c:
        cf._cp(base_cf)
        cf.save()
    can_email_and_edit=1 if request.user==cf.createdbyuser else None
    DispBoolFieldFormSet = modelformset_factory(BoolField,DispBoolFieldForm,extra=0)
    DispIntFieldFormSet = modelformset_factory(IntField,DispIntFieldForm,extra=0)
    if request.method == 'POST':
        if 'email' in request.POST.keys():
            message_subject = 'Please fill out form'
            to_address = request.POST['to_address']#'*****@*****.**'
            from_address = '*****@*****.**'
            message = 'Please visit http://localhost:8000/app/view_cf/%s'%cf_id
            #send_mail(message_subject, message, from_address, [to_address])
            try:
                send_mail(message_subject, message, from_address, [to_address])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return HttpResponseRedirect(reverse('view_cf', args=(cf_id,)))
        else:
            intformset = DispIntFieldFormSet(request.POST,queryset=IntField.objects.filter(for_form=cf),prefix='int')
            boolformset = DispBoolFieldFormSet(request.POST,queryset=BoolField.objects.filter(for_form=cf))
            if intformset.is_valid() and boolformset.is_valid():
                intformset.save()
                boolformset.save()
                print 'theysaved'
            return HttpResponseRedirect(reverse('success'))
    else:
        intformset = DispIntFieldFormSet(queryset=IntField.objects.filter(for_form=cf),prefix='int')
        boolformset = DispBoolFieldFormSet(queryset=BoolField.objects.filter(for_form=cf))
    context = {'base_cf':base_cf,'cf':cf,'intformset':intformset,'boolformset':boolformset,'can_email_and_edit':can_email_and_edit}
    return render(request, 'app/view_form.html', context)
Пример #2
0
def day(request, year, month, day):
    """Entries for the day."""
    entries = Entry.objects.filter(date__year=year, date__month=month,
                                         date__day=day, creator=request.user)
    if len(entries) == 0:
        EntriesFormset = modelformset_factory(Entry, extra=1, exclude=("creator", "date"), can_delete=True)
    else:
        EntriesFormset = modelformset_factory(Entry, extra=0, exclude=("creator", "date"), can_delete=True)
    
    other_entries = []
    if _show_users(request):
        other_entries = Entry.objects.filter(date__year=year, date__month=month,
                                       date__day=day).exclude(creator=request.user)

    if request.method == 'POST':
        formset = EntriesFormset(request.POST)
        if formset.is_valid():
            # add current user and date to each entry & save
            entries = formset.save(commit=False)
            for entry in entries:
                entry.creator = request.user
                entry.date = date(int(year), int(month), int(day))
                entry.save()
            return HttpResponseRedirect(reverse("myproject.views.month", args=(year, month)))

    else:
        # display formset for existing enties and one extra form
        formset = EntriesFormset(queryset=Entry.objects.filter(date__year=year,
            date__month=month, date__day=day, creator=request.user))
    return render_to_response("cal/day.html", add_csrf(request, entries=formset, year=year,
            month=month, day=day, other_entries=other_entries, reminders=reminders(request)),
            context_instance=RequestContext(request))
Пример #3
0
def update_saleairpurchase(request, saleId):
    PurchaseFormSet = modelformset_factory(Purchase, form=PurchaseForm, can_delete=False, can_order=False,extra=0)

    if request.method == 'GET':
        passenger_info = PassengerInfo.objects.filter(is_deleted=False, sales_transaction_no=(Sale.objects.get(id=saleId)))
        purchaseFormIds = [];
        for ticket in passenger_info:
            purchaseFormIds.append(ticket.purchase_transaction_no.id)

        PurchaseFormSet = modelformset_factory(Purchase, form=PurchaseForm, can_delete=False, can_order=False,extra=0)
        purchase_formset = PurchaseFormSet(queryset=Purchase.objects.filter(id__in=purchaseFormIds))

        return render(request, 'themetours/update_saleairpurchase.html', {'purchaseForm' : purchase_formset,
                                                                          'id' : id})
    else:
        purchase_formset = PurchaseFormSet(request.POST)

        if purchase_formset.is_valid():
            for form in purchase_formset:
                model = form.save()
                model.save();
        else:
            return render(request, 'themetours/update_saleairpurchase.html', {'purchaseForm' : purchase_formset,
                                                                              'id' : id},
                          status=302)
    return HttpResponse(model.to_json(), content_type='application/json')
Пример #4
0
def new(request):
    cop_form_set = modelformset_factory(Cop, extra=2)
    image_form_set = modelformset_factory(Images, extra=4, exclude=("thumb"))
    c = {}
    c.update(csrf(request))
    if request.method == "POST":  # if form has been submitted
        incidentForm = IncidentForm(request.POST, prefix="incident")  # a form bound to the POST data
        copFormSet = cop_form_set(request.POST, prefix="cop")
        imageFormSet = image_form_set(request.POST, request.FILES, prefix="images")
        if incidentForm.is_valid() and copFormSet.is_valid() and imageFormSet.is_valid():
            cops = copFormSet.save()
            images = imageFormSet.save()
            incident = incidentForm.save()
            for cop in request.POST["incident-cop_string"].split(","):
                incident.cop.add(Cop.objects.get(badge=cop.strip()))
            for image in images:

                im = Image.open(image.image.path)
                if image.image.width > 1280 or image.image.height > 1280:
                    im.thumbnail((1280, 1280))
                    im.save(image.image.path)
                im.thumbnail((120, 120))
                thumbpath = "incident_thumbs/%s" % image.image.path.split("/")[-1]
                im.save("media/%s" % thumbpath)
                image.thumb = thumbpath
                image.save()
                incident.image.add(image)
            incident.save()
            return HttpResponseRedirect("/incident/%s" % incident.id)
    else:
        incidentForm = IncidentForm(prefix="incident")  # an unbound form
        copFormSet = cop_form_set(queryset=Cop.objects.none(), prefix="cop")
        imageFormSet = image_form_set(queryset=Images.objects.none(), prefix="images")
    c.update({"incident_form": incidentForm, "cop_form": copFormSet, "image_form": imageFormSet})
    return render_to_response("test/new.html", c, context_instance=RequestContext(request))
Пример #5
0
def wizard(request, session):
    data = {
        'user': request.user,
        'character': request.user.character,
        'session': get_object_or_404(Session, pk=session)
    }
    initial = {
        '0': data,
        '1': data,
        '2': data,
    }

    if not data['session'].is_open:
        raise PermissionDenied('Session closed')

    Action.objects.filter(character=request.user.character, session=session).delete()
    ActiveDisciplines.objects.filter(character=request.user.character, session=session).delete()
    Feeding.objects.filter(character=request.user.character, session=session).delete()

    return SubmitWizard.as_view([
        modelformset_factory(ActiveDisciplines,
                            formset=forms.DisciplineActivationFormSet,
                            fields=['disciplines']),
        modelformset_factory(Feeding,
                            formset=forms.FeedingFormSet,
                            fields=['domain', 'feeding_points', 'discipline', 'description']),
        modelformset_factory(Action,
                            formset=forms.ActionFormSet,
                            fields=['action_type', 'description'])],
                            initial_dict=initial)(request, **data)
Пример #6
0
def construire_formset(request):
    assert('espace_membre_etablissement' in request.session)
    e = models.EtablissementModification.objects \
        .get(etablissement=request.session['espace_membre_etablissement'])

    if len(e.get_responsables_set()) != \
            len(e.get_responsables_modification_set()):
        pass

    ResponsableFormset = modelformset_factory(
        models.ResponsableModification, forms.ResponsableForm, extra=0,
        can_delete=False, formset=forms.RequiredFormSet)
    ResponsableFormsetCom = modelformset_factory(
        models.ResponsableModification, forms.ResponsableCommunicationForm,
        extra=1, max_num=1, can_delete=False, formset=forms.RequiredFormSet)

    formset_com = ResponsableFormsetCom(
        request.POST or None,
        queryset=e.get_responsables_modification_com(), prefix='com'
    )
    formset_pha = ResponsableFormset(
        request.POST or None,
        queryset=e.get_responsables_modification_pha(), prefix='pha'
    )

    return formset_pha, formset_com
Пример #7
0
def checkin(request):
	c = RequestContext(request, dictionary)
	CheckinFormSet = modelformset_factory(Checkout, CheckinForm)
	if request.method == "POST":
		data = request.POST.copy()
		for i in range(0, int(data['form-TOTAL_FORMS'])):
			if 'form-' + str(i) + '-return_date' in data:
				data['form-' + str(i) + '-return_date'] = datetime.date.today().isoformat()
			else:
				data['form-' + str(i) + '-return_date'] = ''

		formset = CheckinFormSet(data = data)
		user_form = AutoUserForm(data = data)
		if formset.is_valid():
			c['cool'] = 'cool'
			formset.save()
		else:
			c['err'] = formset.errors
			c['data'] = data
	else:
		CheckinFormSet = modelformset_factory(Checkout, CheckinForm)
		user_form = AutoUserForm()
	c['user_form'] = user_form
	c['form'] = CheckinFormSet
	c['context'] = 'checkin'
	return render_to_response('lib_admin/checkin.html', {}, c)
Пример #8
0
def change_permissions(request, document):
    if request.POST:
        PermissionFormset = modelformset_factory(UserPermission, can_delete=True,
                                                 formset=PermissionChangeFormSet)
        forms = PermissionFormset(request.POST)
        anon_perms = AnonPermissionChangeForm(request.POST, instance=document)
        if forms.is_valid() and anon_perms.is_valid():
            anon_perms.save()
            perms = forms.save(commit=False)
            document.permissions = perms
            document.save()
            messages.success(request, "Permissions changed for '%s'." % document.name)
            return HttpResponseRedirect('/')
    else:
        # Real formset data should be populated via a queryset, but django-nonrel's ListFields
        # return ordinary lists. So we hack around this by turning the objects to dicts, which
        # can be entered as the initial form data, and then bump up the number of extra forms accordingly.
        perms = map(lambda p: p.__dict__, document.permissions)
        PermissionFormset = modelformset_factory(UserPermission,
                                extra= 3 + len(perms), can_delete=True,
                                formset=PermissionChangeFormSet)
        forms = PermissionFormset(initial=perms, queryset=UserPermission.objects.none())

    return render(request, 'permissions.html', {
        'doc': document,
        'forms': forms,
        'anon_perms': AnonPermissionChangeForm(instance=document)
    })
Пример #9
0
def contacto(request):
    """
    Formulario de contacto
    """
    AreasFormSet = modelformset_factory(ViewPort, form=AreaInteresForm, extra=0)
    TelefonoFormSet = modelformset_factory(Telefono, form=TelefonoForm)
    if request.method == 'POST' and "contacto_submit" in request.POST:
        form = ContactoForm(request.POST)
        formset_areas = AreasFormSet(request.POST, prefix="area")
        formset_telefonos = TelefonoFormSet(request.POST, prefix="tel")
        if form.is_valid() and formset_telefonos.is_valid() and \
           formset_areas.is_valid():
            form.save(request, formset_telefonos, formset_areas)

            return direct_response(request, 'portal/contacto_exito.html')
    elif request.method == "POST" and "contacto_proyecto_id" in request.POST:
        proyecto = Proyecto.objects.get(id=request.POST["contacto_proyecto_id"])
        form = ContactoForm(initial={'proyecto': proyecto.id,
                                     "rubros_interes": [proyecto.rubro]})
    else:
        form = ContactoForm()
    formset_areas = AreasFormSet(queryset=ViewPort.objects.none(),
                                 prefix="area")
    formset_telefonos = TelefonoFormSet(queryset=Telefono.objects.none(),
        prefix="tel")

    return direct_response(request, 'portal/contacto.html',
                           {'form': form,
                            'formset_telefonos': formset_telefonos,
                            'formset_areas': formset_areas})
Пример #10
0
def cluster_accounts_new(request, cluster_id):
    """"""
    try:
        cluster = Cluster.objects.get(id = cluster_id)
    except Exception:
        return HttpResponse('this cluster doesn\'t exist')

    if request.method == 'POST':

        ClusterAccountFilledFormSet = modelformset_factory(ClusterAccount,
            form = ClusterAccountForm,
            can_delete = True,
            extra = 0)

        ClusterAccountFormSet = modelformset_factory(ClusterAccount,
            form = ClusterAccountForm,
            extra = 3)

        formset = ClusterAccountFormSet(request.POST)
        formset_filled = ClusterAccountFilledFormSet(request.POST, prefix = 'filled')

        if formset_filled.is_valid():
            formset_filled.save()

        if formset.is_valid():
            for form in formset.save(commit = False):
                form.cluster = cluster
                form.save()

        if 'more' in request.POST:
            return redirect_to(request, '/cluster/%s/provision/accounts/' % cluster_id)
        else:
            return redirect_to(request, '/cluster/%s/provision/' % cluster_id)
Пример #11
0
def registro(request):
    """
    Registro de un usuario
    """
    AreasFormSet = modelformset_factory(ViewPort, form=AreaInteresForm, extra=0)
    TelefonoFormSet = modelformset_factory(Telefono, form=TelefonoForm)
    if request.method == 'POST' and "registro_submit" in request.POST:
        form = RegistroClienteForm(request.POST)
        formset_areas = AreasFormSet(request.POST, prefix="area")
        formset_telefonos = TelefonoFormSet(request.POST, prefix="tel")
        if form.is_valid() and formset_telefonos.is_valid() and \
           formset_areas.is_valid():
            form.save(formset_telefonos, formset_areas)

            return direct_response(request, 'usuarios/confirmacion.html')
    elif request.method == "POST" and "registro_rubro_id" in request.POST:
        rubro = Rubro.objects.get(id=request.POST["registro_rubro_id"])
        form = RegistroClienteForm(initial={"rubros_interes": [rubro]})
    else:
        form = RegistroClienteForm()
    formset_areas = AreasFormSet(queryset=ViewPort.objects.none(),
        prefix="area")
    formset_telefonos = TelefonoFormSet(queryset=Telefono.objects.none(),
                                        prefix="tel")

    return direct_response(request, 'usuarios/registro.html',
                           {'form': form,
                            'formset_telefonos': formset_telefonos,
                            'formset_areas': formset_areas})
Пример #12
0
def update(request, slug):
    meeting = get_object_or_404(Meeting, slug=slug)

    if request.method == 'GET':
        form = MeetingForm(instance=meeting)
        GuestFormSet = modelformset_factory(Guest, fields=('email',), extra=5)
        guest_forms = GuestFormSet()

    elif request.method == 'POST':
        form = MeetingForm(instance=meeting, data=request.POST)
        GuestFormSet = modelformset_factory(Guest, fields=('email',))
        guest_forms = GuestFormSet(request.POST)

        if form.is_valid() and guest_forms.is_valid():
            form.save()
            instances = guest_forms.save(commit=False)
            for instance in instances:
                instance.meeting = meeting
                instance.save()

            return redirect(reverse('meetings_list'))

    return render(request, 'meetings/update.html',
        {
            'meeting': meeting,
            'form': form,
            'guest_forms': guest_forms,
        },
    )
Пример #13
0
def clausulas(request):

	editado = ''
	clausulas = Clausula.objects.filter(id__range=(1,10))
	clausulasFormset = modelformset_factory(Clausula, form=ClausulasForm, extra=1, max_num=2, can_delete=True)
	clausulasF = clausulasFormset(queryset=clausulas)
	notificaciones = Notificacion.objects.all().order_by('created_at')[:10].reverse()

	if request.method == 'POST':
		clausulasFormset = modelformset_factory(Clausula, form=ClausulasForm, extra=1, max_num=2, can_delete=True)
		clausulasF = clausulasFormset(request.POST, request.FILES, queryset=clausulas)

		if clausulasF.is_valid():
			clausulasSet = clausulasF.save(commit=False)
			for clausula in clausulasSet:
				clausula.save()
				editado = True

	ctx = {
		'ClausulasForm':clausulasF,
		'editado':editado,
		'notificaciones':notificaciones,
	}

	return render_to_response('administrador/clausulas/clausulas.html',ctx, context_instance=RequestContext(request))
Пример #14
0
def new(request):
	cop_form_set = modelformset_factory(Cop, extra=2,)
	image_form_set = modelformset_factory(Images, extra=4)
	c = {}
	c.update(csrf(request))
	if request.method == 'POST':#if form has been submitted
		incidentForm = IncidentForm(request.POST, prefix='incident') # a form bound to the POST data
		copFormSet = cop_form_set(request.POST, prefix='cop')
		imageFormSet = image_form_set(request.POST, request.FILES, prefix='images')
		if incidentForm.is_valid() and copFormSet.is_valid() and imageFormSet.is_valid():
			cops = copFormSet.save()
			images = imageFormSet.save()
			incident = incidentForm.save()
			for cop in request.POST['incident-cop_string'].split(','):
				incident.cop.add(Cop.objects.get(badge=cop.strip()))
			for image in images:
				incident.image.add(image)
				image.date = incident.date
				image.save()
			incident.save()	
			return HttpResponseRedirect('/incident/%s'%incident.id)	
	else:
		incidentForm = IncidentForm(prefix='incident') # an unbound form
		copFormSet = cop_form_set(queryset = Cop.objects.none(),prefix='cop')
		imageFormSet = image_form_set(queryset = Images.objects.none(), prefix='images')
	c.update({'incident_form': incidentForm, 'cop_form': copFormSet, 'image_form': imageFormSet})
	return render_to_response('test/new.html', c,
		 context_instance=RequestContext(request))
Пример #15
0
def advance_approved(request):
    if request.user.is_authenticated():
        advance
        userprofile=UserProfile.objects.get(user=request.user)
        advance_approved_form_error=False
        if userprofile.is_core:
            advanceapp123=True #for making the top nav bar active
            approved_submitted=Advance.objects.filter(approved=True).filter(bill_submitted=True)   
            approved_not_submitted=Advance.objects.filter(approved=True).filter(bill_submitted=False)
            ApprovedCoreFormset=modelformset_factory(Advance,fields=('received','receive_date','due_date','core_comment','bill_submitted'))
            if request.method=='POST':
                approved_core_formset=ApprovedCoreFormset(request.POST,queryset=approved_not_submitted)
                for form in approved_core_formset.forms:
                    if form.has_changed():
                        if form.is_valid():
                            form.save()
                        else:
                            advance_approved_form_error=True
                if not advance_approved_form_error:
                    advance_approved_form_success=True
            else:
                approved_core_formset=ApprovedCoreFormset(queryset=approved_not_submitted)
            advanceapp123=True #for making the top nav bar active
            approved_submitted=Advance.objects.filter(approved=True).filter(bill_submitted=True)   
            approved_not_submitted=Advance.objects.filter(approved=True).filter(bill_submitted=False)
            ApprovedCoreFormset=modelformset_factory(Advance,fields=('received','receive_date','due_date','core_comment','bill_submitted'))
            return render_to_response('finance/advance_approved.html',locals(),context_instance=RequestContext(request))    
        else:
            raise Http404
    else:
        raise Http404
Пример #16
0
def bill_purchase_detail_reimb(request,reimb_id,bill_id):
    if request.user.is_authenticated():
        userprofile=UserProfile.objects.get(user=request.user)
        if not userprofile.is_core:
            m=0
            reimb123=True
            PurchaseDetailFormset=modelformset_factory(PurchaseDetail,fields=('item_name','amount'), can_delete=True)
            current_bill=BillDetail.objects.get(id=bill_id)
            qset_purchase=PurchaseDetail.objects.filter(bill=current_bill)
            if request.method=='POST':
                purchasedetailformset=PurchaseDetailFormset(request.POST,queryset=qset_purchase)
                for form in purchasedetailformset.forms:
                    if form.has_changed():
                        if form not in purchasedetailformset.deleted_forms:
                            form_instance=form.save(commit=False)
                            bill2=BillDetail.objects.get(id=bill_id)
                            form_instance.bill=bill2
                            form_instance.save()
                        else:
                            if PurchaseDetail.objects.filter(id=form.instance.id):
                                form_instance=PurchaseDetail.objects.get(id=form.instance.id)
                                form_instance.delete()
                if "add_more" in request.POST:
                    m=2 
                    PurchaseDetailFormset=modelformset_factory(PurchaseDetail,fields=('item_name','amount'),extra=m, can_delete=True)
            qset_purchase=PurchaseDetail.objects.filter(bill=current_bill)
            purchasedetailformset=PurchaseDetailFormset(queryset=qset_purchase)
            return render_to_response('finance/bill_purchase_detail_reimb.html',locals(),context_instance=RequestContext(request))
    else:
        return Http404
Пример #17
0
def contact_create(request):
    # Create formsets for phone & webaddress models
    PhoneFormSet = modelformset_factory(Phone, form=PhoneForm, extra=1, max_num=4)
    WebAddressFormSet = modelformset_factory(WebAddress, form=WebAddressForm, extra=1, max_num=4)
    if request.method == "POST":
        contact_form = ContactForm(request.POST)
        phone_formset = PhoneFormSet(request.POST, prefix='phone')
        webaddress_formset = WebAddressFormSet(request.POST, prefix='webaddress')
        if contact_form.is_valid() and phone_formset.is_valid() and webaddress_formset.is_valid():
            contact = contact_form.save()
            # Save details for Phone FormSet
            for phone_form in phone_formset:
                phone_form = phone_form.save(commit=False)
                phone_form.contact_id = contact.id
                phone_form.save()
            # Save details for WebAddress FormSet
            for webaddress_form in webaddress_formset:
                webaddress_form = webaddress_form.save(commit=False)
                webaddress_form.contact_id = contact.id
                webaddress_form.save()
            return redirect('contacts:detail', contact.slug)
    else:
        contact_form = ContactForm()
        phone_formset = PhoneFormSet(queryset=Phone.objects.none(), prefix='phone')
        webaddress_formset = WebAddressFormSet(queryset=WebAddress.objects.none(), prefix='webaddress')

        return render(request, 'contacts/contact_create.html',
                      {'contact_form': contact_form,
                       'phone_formset': phone_formset,
                       'webaddress_formset': webaddress_formset}
                      )
Пример #18
0
def company_delete(request, slug):
    company = get_object_or_404(Company, slug=slug)
    address = Address.objects.filter(company=company)
    AddressFormSet = modelformset_factory(Address, form=DeleteAddressForm)
    phone = Phone.objects.filter(company=company)
    PhoneFormSet = modelformset_factory(Phone, form=DeletePhoneForm)
    webaddress = WebAddress.objects.all().filter(company=company)
    WebAddressFormSet = modelformset_factory(WebAddress, form=DeleteWebAddressForm)
    if request.method == "POST":
        company_form = DeleteCompanyForm(request.POST, instance=company)
        address_formset = AddressFormSet(request.POST, queryset=address)
        phone_formset = PhoneFormSet(request.POST, queryset=phone)
        webaddress_formset = WebAddressFormSet(request.POST, queryset=webaddress)
        if company_form.is_valid()and address_formset.is_valid and phone_formset.is_valid and webaddress_formset.is_valid:
            company.delete()
            address.delete()
            phone.delete()
            webaddress.delete()
            return redirect('companies:list')
    else:
        company_form = CompanyForm(instance = company)
        address_formset = AddressFormSet(queryset=address)
        phone_formset = PhoneFormSet(queryset=phone)
        webaddress_formset = WebAddressFormSet(queryset=webaddress)
        return render(request, 'companies/company_delete.html',
                      {'company': company,
                       'company_form': company_form,
                       'address_formset': address_formset,
                       'phone_formset': phone_formset,
                       'webaddress_formset': webaddress_formset}
                      )
Пример #19
0
def precios(request,ano=None,mes=None,dia=None,mercado=None):
	app_label="precios"
	model_label="prueba"
	title="Añadir precios de una fecha en un mercado"
	if ano == None:
		if ('mercado' in request.GET) and request.GET['mercado'].strip():
                	mercado = request.GET['mercado']
                	ano = request.GET['ano']
                	mes = request.GET['mes']
                	dia = request.GET['dia']
			return HttpResponseRedirect("/admin/precios/prueba/bulk_add/"+mercado+"/"+ano+"/"+mes+"/"+dia+"/")
		else:
			form=PreciosParameterForm()
			return render_to_html(request,"bulk_add_form_firstpage.html", {'form':form,'app_label':app_label,'model_label':model_label,'title':title})
	else:
		next_set_description="Grabar y añadir datos del proximo mercado"
		if request.method == "POST":
			PreciosPruebaFormSet = modelformset_factory(PreciosPrueba)
			data = request.POST.copy()
			form = PreciosPruebaFormSet(data=data)
			if form.is_valid():
				form.save()
			else:
				return render_to_html(request,"bulk_add_form.html", {"form":form,"next_set_description":next_set_description,"app_label":app_label,"model_label":model_label,"title":title})
			if data.has_key('_next_set'):
				mercado=int(mercado)
				if mercado < len(Mercado.objects.all()):
					mercado = 1
				mercado=str(mercado)
				return HttpResponseRedirect("/admin/precios/prueba/bulk_add/"+mercado+"/"+ano+"/"+mes+"/"+dia+"/")
			elif data.has_key('_continue_editing'):
				return HttpResponseRedirect("/admin/precios/prueba/bulk_add/"+mercado+"/"+ano+"/"+mes+"/"+dia+"/")
			else:
				return HttpResponseRedirect("/admin/precios/")
		else:
			queryset=PreciosPrueba.objects.filter(fecha__year=int(ano)).filter(fecha__month=int(mes)).filter(fecha__day=int(dia)).filter(mercado=int(mercado))
			mercado_object=Mercado.objects.get(id=int(mercado))
			if mercado_object.mayor==True:
				productos=Producto.objects.filter(se_vende_en_mayor=True)
			else:
				productos=Producto.objects.filter(se_vende_en_menor=True)
			if len(queryset) > 0:
				PreciosPruebaFormSet = modelformset_factory(PreciosPrueba,extra=(len(productos)-len(queryset)))
				form = PreciosPruebaFormSet(queryset=queryset)
			else:
				initial_list=[]
				if mes > 9:
					mes_str=str(mes)
				else:
					mes_str="0"+str(mes)
				if dia > 9:
					dia_str=str(dia)
				else:
					dia_str="0"+str(dia)
				for producto in productos.iterator():
					initial_list.append({'mercado':str(mercado),'producto':str(producto.id),'fecha':str(ano)+'-'+mes_str+'-'+dia_str})
				PreciosPruebaFormSet = modelformset_factory(PreciosPrueba,extra=len(initial_list))
				form = PreciosPruebaFormSet(initial=initial_list,queryset=PreciosPrueba.objects.none())
			return render_to_html(request,"bulk_add_form.html", {"form":form,"next_set_description":next_set_description,"app_label":app_label,"model_label":model_label,"title":title})
Пример #20
0
def teaching_graduate(request):
    formInfo = {
    }
    formsetInfo = {
        'advisor': (
            modelformset_factory(GradAdvisor, form=AdvisorForm, extra=0,
                formset=FormsetMixin, can_delete=True),
            {
                'queryset': GradAdvisor.objects.filter(user=request.user),
                'prefix': 'gradad',
                'pk': request.user.id,
                'label': 'Advisor'
            }
        ),
        'committee': (
            modelformset_factory(GradAdvisorCommitteeMember, form=AdvisorCommitteeForm, extra=0,
                formset=FormsetMixin, can_delete=True),
            {
                'queryset': GradAdvisorCommitteeMember.objects.filter(user=request.user),
                'prefix': 'gradmem',
                'pk': request.user.id,
                'label': 'Advising Committee Member'
            }
        ),
        'examiner': (
            modelformset_factory(GradExaminer, form=ExaminerForm, extra=0,
                formset=FormsetMixin, can_delete=True),
            {
                'queryset': GradExaminer.objects.filter(user=request.user),
                'prefix': 'gradexam',
                'pk': request.user.id,
                'label': 'Examining Committee Member'
            }
        )
    }

    if request.method == 'POST':
        formsets, forms = createContext(formsetInfo, formInfo,
                postData=request.POST, files=request.FILES)
        context = dict([('forms', forms), ('formsets', formsets)])

        allForms = dict(formsets)
        allForms.update(forms)

        if reduce(lambda f1, f2: f1 and f2.is_valid(), allForms.values(), True):
            # Save the form data, ensure they are updating as themselves
            for form in forms.values():
                form.save()
            for formset in formsets.values():
                formset.save()

            return HttpResponseRedirect(reverse('cv-teaching-graduate'))

    else:
        formsets, forms = createContext(formsetInfo, formInfo)
        context = dict([('forms', forms), ('formsets', formsets)])

    return direct_to_template(request, 'teaching_graduate.html', context)
Пример #21
0
def lluvia(request,ano=None,mes=None,estacion_de_lluvia=None):
	app_label="lluvia"
	model_label="prueba"
	title="Añadir mes de lluvia"
	if ano == None:
		if ('estacion_de_lluvia' in request.GET) and request.GET['estacion_de_lluvia'].strip():
                	estacion_de_lluvia = request.GET['estacion_de_lluvia']
                	ano = request.GET['ano']
                	mes = request.GET['mes']
			return HttpResponseRedirect("/admin/lluvia/prueba/bulk_add/"+estacion_de_lluvia+"/"+ano+"/"+mes+"/")
		else:
			form=LluviaParameterForm()
			return render_to_html(request,"bulk_add_form_firstpage.html", {'form':form,'app_label':app_label,'model_label':model_label,'title':title})
	else:
		next_set_description="Grabar y añadir proximo mes"
		if request.method == "POST":
			LluviaPruebaFormSet = modelformset_factory(LluviaPrueba)
			data = request.POST.copy()
			form = LluviaPruebaFormSet(data=data)
			if form.is_valid():
				form.save()
			else:
				return render_to_html(request,"bulk_add_form.html", {"form":form,"next_set_description":next_set_description,"app_label":app_label,"model_label":model_label,"title":title})
			if data.has_key('_next_set'):
				mes=int(mes)
				ano=int(ano)
				if mes < 12:
					mes += 1
				else:
					ano += 1
					mes = 1
				mes=str(mes)
				ano=str(ano)
				return HttpResponseRedirect("/admin/lluvia/prueba/bulk_add/"+estacion_de_lluvia+"/"+ano+"/"+mes+"/")
			elif data.has_key('_continue_editing'):
				return HttpResponseRedirect("/admin/lluvia/prueba/bulk_add/"+estacion_de_lluvia+"/"+ano+"/"+mes+"/")
			else:
				return HttpResponseRedirect("/admin/lluvia/")
		else:
			queryset=LluviaPrueba.objects.filter(fecha__year=int(ano)).filter(fecha__month=int(mes)).filter(estacion=int(estacion_de_lluvia))
			if len(queryset) > 0:
				LluviaPruebaFormSet = modelformset_factory(LluviaPrueba,extra=(calendar.monthrange(int(ano),int(mes))[1]-len(queryset)))
				form = LluviaPruebaFormSet(queryset=queryset)
			else:
				initial_list=[]
				for dia in range(1,calendar.monthrange(int(ano),int(mes))[1]+1):
					if mes > 9:
						mes_str=str(mes)
					else:
						mes_str="0"+str(mes)
					if dia > 9:
						dia_str=str(dia)
					else:
						dia_str="0"+str(dia)
					initial_list.append({'estacion':str(estacion_de_lluvia),'milimetros_de_lluvia':'0.0','fecha':str(ano)+'-'+mes_str+'-'+dia_str})
				LluviaPruebaFormSet = modelformset_factory(LluviaPrueba,extra=len(initial_list))
				form = LluviaPruebaFormSet(initial=initial_list,queryset=LluviaPrueba.objects.none())
			return render_to_html(request,"bulk_add_form.html", {"form":form,"next_set_description":next_set_description,"app_label":app_label,"model_label":model_label,"title":title})
Пример #22
0
def upload_corrections(request, paper_id=0, review_id=0):
    dict = {}
    ap = AuthorProfile.objects.get(user=request.user)
    paper = Paper.objects.all().filter(author=ap).filter(id=paper_id).first()
    review = Review.objects.get(id=review_id)

    paper_factory = modelformset_factory(ReviewPaperComments, extra=0, form=AuthorPaperCommentsForm)
    paper_formset = paper_factory(request.POST or None, queryset=ReviewPaperComments.objects.all().filter(review_id=review.review_paper), prefix='fs1')
    paper_helper = AuthorPaperCommentsHelper()

    theses_factory = modelformset_factory(ReviewThesesComments, extra=0, form=AuthorThesesCommentsForm)
    theses_formset = theses_factory(request.POST or None, queryset=ReviewThesesComments.objects.all().filter(review_id=review.review_theses), prefix='fs2')
    theses_helper = AuthorThesesCommentsHelper()

    if paper.paper_file:
        paper_file_form = AuthorCorrPaperForm(request.POST or None, request.FILES or None, instance=paper)
    else:
        paper_file_form = None

    if paper.theses_file:
        theses_file_form = AuthorCorrThesesForm(request.POST or None, request.FILES or None, instance=paper)
    else:
        theses_file_form = None
    # UPLOAD CORRECTED PAPER FORM

    if request.method == 'POST':
        if paper_formset.is_valid() and theses_formset.is_valid():
            is_valid = True
            if paper_file_form:
                if not paper_file_form.is_valid():
                    is_valid = False
                else:
                    paper_file_form.save(commit=False)

            if theses_file_form:
                if not theses_file_form.is_valid():
                    is_valid = False
                else:
                    theses_file_form.save(commit=False)
            if is_valid:
                paper_formset.save()
                theses_formset.save()
                if paper_file_form:
                    paper_file_form.save()
                if theses_file_form:
                    theses_file_form.save()
                return redirect('/profile/#author')



    dict['paper_formset'] = paper_formset
    dict['theses_formset'] = theses_formset
    dict['paper_helper'] = paper_helper
    dict['theses_helper'] = theses_helper
    dict['paper_file_form'] = paper_file_form
    dict['theses_file_form'] = theses_file_form

    return render(request, 'upload_corrections.html', dict)
Пример #23
0
def media_formset(request,queryset,prefix='media',*args,**kwargs):
    
    if request == None or request.method=='GET':
        return modelformset_factory(MediaFile,form=MediaFileForm 
                        )(queryset=queryset,prefix=prefix,*args,**kwargs)
    else:
        return modelformset_factory(MediaFile,form=MediaFileForm
                        )(request.POST,request.FILES,
                          queryset=queryset,prefix=prefix,*args,**kwargs)
Пример #24
0
def get_resume_formset(member):
    if member and member.educational_resumes.exists():
        ResumeForm = modelformset_factory(EducationalResume, form=EducationalResumeModelForm,
                                          exclude=('cluster_member', ),
                                          can_delete=True, extra=0)
    else:
        ResumeForm = modelformset_factory(EducationalResume, form=EducationalResumeModelForm,
                                          exclude=('cluster_member', ),
                                          can_delete=True)
    return ResumeForm
Пример #25
0
def advance(request):
    if request.user.is_authenticated():
        userprofile=UserProfile.objects.get(user=request.user)
        if not userprofile.is_core:
            if request.method=='POST':
                advanceform=AdvanceForm(request.POST)
                if advanceform.is_valid():
                    advanceform1=advanceform.save(commit=False)
                    advanceform1.applied_date=date.today()
                    advanceform1.project=userprofile.project
                    advanceform1.save()
                    advanceform_success=True
                    advanceform=AdvanceForm()
                else:
                    advanceform_error=True
                    
                if "read" in request.POST:  
                    read1=Advance.objects.filter(project=userprofile.project).filter(approved=False).filter(disapproved=True).filter(read=False)
                    for read2 in read1:
                        read2.read=True
                        read2.save()
                    advanceform_error=False
                #return HttpResponseRedirect('/advance')
            else:
                advanceform=AdvanceForm()  
            advance123=True #for making the top nav bar active
            advance_applications=Advance.objects.filter(project=userprofile.project).order_by('-applied_date')
            number_await_approval=len(Advance.objects.filter(project=userprofile.project).filter(approved=False).filter(disapproved=False))
            number_approved_not_rec=len(Advance.objects.filter(project=userprofile.project).filter(approved=True).filter(received=False))
            number_rec_add_bills=len(Advance.objects.filter(project=userprofile.project).filter(approved=True).filter(received=True).filter(bill_submitted=False))
            number_disapproved_unread=len(Advance.objects.filter(project=userprofile.project).filter(approved=False).filter(disapproved=True).filter(read=False))
            advance_applications_awaiting_approval=Advance.objects.filter(project=userprofile.project).filter(approved=False).filter(disapproved=False).order_by('-applied_date')
            approved_not_rec=Advance.objects.filter(project=userprofile.project).filter(approved=True).filter(received=False).order_by('-approved_date')
            rec_add_bills=Advance.objects.filter(project=userprofile.project).filter(approved=True).filter(received=True).filter(bill_submitted=False).order_by('-receive_date')
            disapproved_unread=Advance.objects.filter(project=userprofile.project).filter(approved=False).filter(disapproved=True).filter(read=False).order_by('-applied_date')
            return render_to_response('finance/advance.html',locals(),context_instance=RequestContext(request))     
        else:
            advancereq123=True #for making the top nav bar active
            pending_advance_app=Advance.objects.filter(approved=False).filter(disapproved=False)
            AdvanceCoreFormset=modelformset_factory(Advance,fields=('approved','disapproved','core_comment',))
            if request.method=='POST':
                advance_core_formset=AdvanceCoreFormset(request.POST,queryset=pending_advance_app)
                for form in advance_core_formset.forms:
                    if form.has_changed():
                        form.save()
                advance_request_form_success=True
            else:
                advance_core_formset=AdvanceCoreFormset(queryset=pending_advance_app)
            advancereq123=True #for making the top nav bar active
            pending_advance_app=Advance.objects.filter(approved=False).filter(disapproved=False)
            AdvanceCoreFormset=modelformset_factory(Advance,fields=('approved','disapproved','core_comment',))
                
        return render_to_response('finance/advance.html',locals(),context_instance=RequestContext(request))      
    else:
        raise Http404        
Пример #26
0
def step_3(request, trial_pk):
    ct = get_object_or_404(ClinicalTrial, id=int(trial_pk))

    GeneralDescriptorSet = modelformset_factory(Descriptor,
                                                form=GeneralHealthDescriptorForm,
                                                extra=EXTRA_FORMS)

    SpecificDescriptorSet = modelformset_factory(Descriptor,
                                                form=SpecificHealthDescriptorForm,
                                                extra=EXTRA_FORMS)

    general_qs = Descriptor.objects.filter(trial=trial_pk,
                                           aspect=choices.TRIAL_ASPECT[0][0],
                                           level=choices.DESCRIPTOR_LEVEL[0][0])

    specific_qs = Descriptor.objects.filter(trial=trial_pk,
                                           aspect=choices.TRIAL_ASPECT[0][0],
                                           level=choices.DESCRIPTOR_LEVEL[1][0])

    if request.POST:
        form = HealthConditionsForm(request.POST, instance=ct)
        gdesc = GeneralDescriptorSet(request.POST,queryset=general_qs,prefix='g')
        sdesc = SpecificDescriptorSet(request.POST,queryset=specific_qs,prefix='s')

        if form.is_valid() and gdesc.is_valid() and sdesc.is_valid():

            for cdata in gdesc.cleaned_data+sdesc.cleaned_data:
                cdata['trial'] = ct

            form.save()
            gdesc.save()
            sdesc.save()

            if request.POST.has_key('submit_next'):
                return HttpResponseRedirect(reverse("step_4",args=[trial_pk]))

            return HttpResponseRedirect(reverse("repository.edittrial", args=[trial_pk]))
    else:
        form = HealthConditionsForm(instance=ct)
        gdesc = GeneralDescriptorSet(queryset=general_qs,prefix='g')
        sdesc = SpecificDescriptorSet(queryset=specific_qs,prefix='s')


    forms = [form]
    formsets = [gdesc, sdesc]
    return render_to_response('repository/step_3.html',
                              {'forms':forms,'formsets':formsets,
                               'username':request.user.username,
                               'trial_pk':trial_pk,
                               'title':TRIAL_FORMS[2],
                               'steps': step_list(trial_pk),
                               'next_form_title':_('Interventions Form')})
Пример #27
0
def company_edit(request, slug):
    company = get_object_or_404(Company, slug=slug)
    address = Address.objects.filter(company=company)
    AddressFormSet = modelformset_factory(Address, form=AddressForm, extra=0, max_num=4)
    phone = Phone.objects.filter(company=company)
    PhoneFormSet = modelformset_factory(Phone, form=PhoneForm, extra=0, max_num=4)
    webaddress = WebAddress.objects.all().filter(company=company)
    WebAddressFormSet = modelformset_factory(WebAddress, form=WebAddressForm, extra=0, max_num=4)
    if request.method == "POST":
        company_form = CompanyForm(request.POST, instance=company)
        address_formset = AddressFormSet(request.POST, queryset=address, prefix='address')
        phone_formset = PhoneFormSet(request.POST, queryset=phone, prefix='phone')
        webaddress_formset = WebAddressFormSet(request.POST, queryset=webaddress, prefix='webaddress')
        if company_form.is_valid() and address_formset.is_valid() and phone_formset.is_valid() and webaddress_formset.is_valid():
            company = company_form.save()
            # Save details for Address FormSet
            for address_form in address_formset:
                address_form = address_form.save(commit=False)
                address_form.company_id = company.id
                address_form.save()
            # Save details for Phone FormSet
            for phone_form in phone_formset:
                phone_form = phone_form.save(commit=False)
                phone_form.company_id = company.id
                phone_form.save()
            # Save details for WebAddress FormSet
            for webaddress_form in webaddress_formset:
                webaddress_form = webaddress_form.save(commit=False)
                webaddress_form.company_id = company.id
                webaddress_form.save()
            return redirect('companies:detail', company.slug)
        else:
            return redirect('companies:list')
    else:
        company_form = CompanyForm(instance=company)
        address_formset = AddressFormSet(queryset=address, prefix='address')
        phone_formset = PhoneFormSet(queryset=phone, prefix='phone')
        webaddress_formset = WebAddressFormSet(queryset=webaddress, prefix='webaddress')
        if address_formset.total_form_count() == 0:
             address_formset.extra=1
        if phone_formset.total_form_count() == 0:
             phone_formset.extra=1
        if webaddress_formset.total_form_count() == 0:
             webaddress_formset.extra=1
        return render(request, 'companies/company_edit.html',
                      {'company': company,
                       'company_form': company_form,
                       'address_formset': address_formset,
                       'phone_formset': phone_formset,
                       'webaddress_formset':webaddress_formset}
                      )
Пример #28
0
def month(request, year=time.localtime()[0], month=time.localtime()[1], change=None):
    """Listing of days in `month`."""
    year, month = int(year), int(month)

    # apply next / previous change
    if change in ("next", "prev"):
        now, mdelta = date(year, month, 15), timedelta(days=31)
        if change == "next":   mod = mdelta
        elif change == "prev": mod = -mdelta

        year, month = (now+mod).timetuple()[:2]

    # init variables
    cal = calendar.Calendar()
    month_days = cal.itermonthdays(year, month)
    nyear, nmonth, nday = time.localtime()[:3]
    lst = [[]]
    week = 0

    # make month lists containing list of days for each week
    # each day tuple will contain list of entries and 'current' indicator
    for day in month_days:
        entries = current = False   # are there entries for this day; current day?
        form = None
        filled = False
        formset = 0
        if day:
            entries = Entry.objects.filter(date__year=year, date__month=month, date__day=day, creator=request.user)
            if not _show_users(request):
                entries = entries.filter(creator=request.user)
            if day == nday and year == nyear and month == nmonth:
                current = True
                
            if len(entries) == 0:
                form = modelformset_factory(Entry, extra=1, exclude=("creator", "date"), can_delete=True)
            else:
                form = modelformset_factory(Entry, extra=0, exclude=("creator", "date"), can_delete=True)
                filled = True
                
            formset = form(queryset=Entry.objects.filter(date__year=year,
            date__month=month, date__day=day, creator=request.user))

        lst[week].append((day, entries, current, formset, filled))
        if len(lst[week]) == 7:
            lst.append([])
            week += 1

    return render_to_response("cal/month.html", dict(year=year, month=month, user=request.user,
                        month_days=lst, mname=mnames[month-1], reminders=reminders(request)),
                        context_instance=RequestContext(request))
Пример #29
0
def local(request, document_id, grade):

    document = get_object_or_404(Document, pk=document_id)
    if request.method == 'POST':
        WordFormSet = modelformset_factory(
            LocalWord, 
            form=RestrictedWordForm,
            exclude=('document', 'isConfirmed', 'isDeferred', 'grade'), 
            can_delete=True)

        formset = WordFormSet(request.POST, 
                              queryset=LocalWord.objects.filter(grade=grade, document=document))
        if formset.is_valid():
            instances = formset.save()
            writeLocalTables([document])
            redirect = 'dictionary_local_g1' if grade == 1 else 'dictionary_local_g2'
            return HttpResponseRedirect(reverse(redirect, args=[document_id]))
        else:
            return render_to_response('dictionary/local.html', locals(),
                                      context_instance=RequestContext(request))

    filterform = FilterForm(request.GET)
    if filterform.is_valid():
        currentFilter = filterform.cleaned_data['filter']
    
    words_list = LocalWord.objects.filter(grade=grade, document=document,
                                          untranslated__contains=currentFilter).order_by('untranslated', 'type')
    paginator = Paginator(words_list, MAX_WORDS_PER_PAGE)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    
    try:
        words = paginator.page(page)
    except InvalidPage:
        words = paginator.page(paginator.num_pages)

    WordFormSet = modelformset_factory(
        LocalWord, 
        form=RestrictedWordForm,
        exclude=('document', 'isConfirmed', 'isDeferred', 'grade'), 
        can_delete=True, extra=0)

    formset = WordFormSet(queryset=words.object_list)

    return render_to_response('dictionary/local.html', locals(), 
                              context_instance=RequestContext(request))
Пример #30
0
def edit_workout(request, workout_id):
    c = {}
    print request.POST
    c.update(csrf(request))
    workout = get_object_or_404(Workout, pk=workout_id)
    team = Member.objects.get(user=request.user).team
    if request.method == 'POST': # If the form has been submitted...
        workoutForm = WorkoutForm(request.POST) #for update pass in instance=w
        if workoutForm.is_valid():
            workout.name = workoutForm.cleaned_data['name']
            workout.kind = workoutForm.cleaned_data['kind']
            formset_cls = modelformset_factory(Step, fields=('activity',
                    'duration'),
                    form = make_model_step_form(team), can_delete=True, can_order=True)
            formset = formset_cls(request.POST)
            if formset.is_valid():
                # DELETE ALL STEPS then recreate in order -> Helps with ordering
                # issues and wrong numbering etc...
                Step.objects.filter(workout=workout).delete()
                #for form in formset.ordered_forms:
                #    print "USE: ", form.cleaned_data
                #for form in formset.deleted_forms:
                #    print "DELETE: ", form.cleaned_data
                workout.save()
                i = 0
                for form in formset.ordered_forms:
                    step = Step(workout=workout,
                            activity=form.cleaned_data['activity'],
                            position = i,
                            duration = form.cleaned_data['duration'])
                    i = i + 1
                    step.save()
                
                messages.add_message(request, messages.SUCCESS, 'Workout Updated!')
                return HttpResponseRedirect(reverse('workout_details', args=(workout.id,)))
            else:
                print formset.errors
    else:
        workoutForm = WorkoutForm(instance=workout)
        Formset = modelformset_factory(Step, extra=1,
        fields=('activity','duration'),
                    can_order=True, can_delete=True,
                    form=make_model_step_form(team))
        formset = Formset(queryset=Step.objects.filter(workout=workout))
    return render_to_response("workouts/edit.html", 
            {'workout': workoutForm, 'form': formset, 
                'workout_id': workout.id, 'c':c},
                               context_instance=RequestContext(request))
Пример #31
0
    title = forms.CharField(label='Название',
                widget=forms.TextInput(attrs={'class': 'form-control'}))
    max_time = forms.IntegerField(label='Время, отведенное на тест (в минутах)',
                widget=forms.TextInput(attrs={'class': 'form-control'}))
    max_answers = forms.IntegerField(label='Сколько вариантов ответов отображать',
                widget=forms.TextInput(attrs={'class': 'form-control'}))
    description = forms.CharField(label='Описание',
                                  widget=forms.Textarea(
                                    {
                                        'cols': '50', 'rows': '4',
                                        'class': 'form-control'
                                    }
                                  ))


QuestionSetFormSet = modelformset_factory(QuestionSet, QuestionSetForm, extra=0)


class QuestionForm(forms.ModelForm):

    class Meta():
        model = Question
        fields = ['html_text', 'image']

    html_text = forms.CharField(label='Текст вопроса',
                                widget=forms.Textarea(
                                    {
                                        'cols': '50', 'rows': '4',
                                        'class': 'form-control'
                                    }
                                ))
Пример #32
0
from django import forms

from django.forms.models import modelformset_factory


from .models import Variation, Category, Brand, Collection



class VariationInventoryForm(forms.ModelForm):
	class Meta:
		model = Variation
		fields = [
			"price",
			"sale_price",
			"inventory",
			"active",
		]


VariationInventoryFormSet = modelformset_factory(Variation, form=VariationInventoryForm, extra=0)
Пример #33
0
def posterboards_handler(request,
                         blogger=None,
                         posterboard=None,
                         format='html'):
    user = request.user
    data = {}

    # Extra check for redundancy. This is already handled in the decorator.
    if blogger is None:
        logger.info("Attempt to access PB without blogger o.O")
        return HttpResponseForbidden('Please specify a blogger first.')

    # index
    if request.method == 'GET' and posterboard is None:
        if blogger.id == user.id:
            pbs = blogger.posterboard_set.all()
        else:
            pbs = blogger.posterboard_set.filter(is_private=False).all()

        if format == 'html':
            return render_to_response('posterboards/index.html', {
                'blogger': blogger,
                'posterboards': pbs
            },
                                      context_instance=RequestContext(request))
        elif format == 'json':
            # Serialize object .. then get actual data structure out of serialized string
            data['posterboards'] = eval(serializers.serialize('json', pbs))
            # Then serialize again.
            return HttpResponse(json.dumps(data), mimetype='application/json')

    # show
    elif request.method == 'GET' and posterboard is not None:
        if blogger.id != user.id and posterboard.is_private:
            return HttpResponseForbidden('Private Posterboard.')

        if format == 'html':
            ElementFormSet = modelformset_factory(PBElement)
            e = ElementFormSet()
            return render_to_response('posterboards/show.html', {
                'blogger': blogger,
                'posterboard': posterboard,
                'element': e
            },
                                      context_instance=RequestContext(request))
        elif format == 'json':
            data['posterboard'] = eval(
                serializers.serialize('json', posterboard))
            return HttpResponse(json.dumps(data), mimetype='application/json')

    # create
    elif request.method == 'POST':
        form = PosterboardForm(request.POST)
        if form.is_valid():
            # commit=False returns the model object but doesn't save it.
            posterboard = form.save(commit=False)
            # Do some stuff if necessary.
            # ...
            # Just demonstrating here how we can separately save the PB.
            posterboard.save()
            user.posterboard_set.add(posterboard)

            if format == 'html':
                # A redirect with this object will redirect to the url
                # specified as the permalink in that model.
                # More info:
                # http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect
                return redirect(posterboard)
            elif format == 'json':
                data['message'] = 'Posterboard created successfully.'
                data['posterboard'] = serializers.serialize(
                    'json', posterboard)
                return HttpResponse(json.dumps(data),
                                    mimetype='application/json')
        else:
            data['errors'] = 'Posterboard data isn\'t valid.'
            if format == 'html':
                return redirect(user, data)
            elif format == 'json':
                return HttpResponseBadRequest(json.dumps(data),
                                              mimetype='application/json')

    # destroy
    elif request.method == 'DELETE' and posterboard is not None and \
            blogger.id == user.id:
        if format == 'html':
            return redirect(blogger)
        elif format == 'json':
            data[
                'message'] = 'Successfully removed posterboard ' + posterboard.id
            return HttpResponse(json.dumps(data), mimetype='application/json')

    # All other types of requests are invalid for this specific scenario.
    error = {'errors': 'Invalid request'}
    if format == 'html':
        return redirect(blogger)
    elif format == 'json':
        return HttpResponse(json.dumps(error),
                            mimetype='application/json',
                            status=400)
Пример #34
0
from olympia.addons.models import Addon
from olympia.files.models import File

LOGGER_NAME = 'z.zadmin'
log = olympia.core.logger.getLogger(LOGGER_NAME)


class AddonStatusForm(ModelForm):
    class Meta:
        model = Addon
        fields = ('status', )


class FileStatusForm(ModelForm):
    class Meta:
        model = File
        fields = ('status', )

    def clean_status(self):
        changed = not self.cleaned_data['status'] == self.instance.status
        if changed and self.instance.version.deleted:
            raise forms.ValidationError(
                ugettext('Deleted versions can`t be changed.'))
        return self.cleaned_data['status']


FileFormSet = modelformset_factory(File,
                                   form=FileStatusForm,
                                   formset=BaseModelFormSet,
                                   extra=0)
Пример #35
0
        self.helper.form_tag = False
        self.render_unmentioned_fields = True

        self.helper.layout = Layout(
            Row(
                Column('name', css_class='medium-5'),
                Column('uri', css_class='medium-5'),
                Column(HTML('<label>&nbsp;</label>'),
                       CheckBox('DELETE'),
                       css_class='link-delete medium-2'),
            ), )


NavbarLinkFormSet = modelformset_factory(NavbarLink,
                                         exclude=('account', ),
                                         form=NavbarlinkForm,
                                         extra=2,
                                         can_delete=1)


class ChangePasswordForm(forms.Form):
    """Form for changing password for an account"""
    old_password = forms.CharField(label='Old password',
                                   widget=forms.widgets.PasswordInput)
    new_password1 = forms.CharField(label='New password (>= 8 characters)',
                                    min_length=Account.MIN_PASSWD_LENGTH,
                                    widget=forms.widgets.PasswordInput)
    new_password2 = forms.CharField(label='Repeat password',
                                    min_length=Account.MIN_PASSWD_LENGTH,
                                    widget=forms.widgets.PasswordInput)
Пример #36
0
def get_ra_question_statements(request, ra_question_id, ra_section_id,
                               assessment_id):
    """
    View for ra question statements
    :param request:
    :param ra_question_id:
    :param ra_section_id:
    :param assessment_id:
    :return:
    """
    assessment = Assessment.objects.get(pk=assessment_id)
    ra_section = RiskAssessmentSection.objects.get(pk=ra_section_id)
    RAQuestionStatmentFormSet = \
        modelformset_factory(AssessmentRAQuestionStatement,
                             max_num=len(assessment.hazards.all()))

    question_statement = \
        AssessmentRAQuestionStatement.objects.get(pk = ra_question_id)
    files_to_show = \
        ('short_term_value','mid_term_value','long_term_value','mov')

    if request.method == 'POST':
        formset = RAQuestionStatmentFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            ra_questionset_list = \
                RiskAssessmentQuestionset.objects.filter(ra_section =
                                                         ra_section_id)
            question_list = \
                RiskAssessmentQuestion.objects.filter(ra_questionset =
                                                      ra_questionset_list).\
                    order_by('id')
            paginator = Paginator(question_list, 25)  # Show 25 items per page
            page = request.GET.get('page')
            try:
                questions = paginator.page(page)
            except:
                questions = paginator.page(1)
            return render_to_response(
                'crptapp/ra_questions.html', {
                    "questions": questions,
                    "assessment": assessment,
                    "ra_section": ra_section,
                })
        else:
            if format(len(formset.errors) > 0):
                num_errors = len(formset.errors[0])
        set_ra_statements_hidden_fields(formset, files_to_show)
        #set_ra_statements_readonly_fields(formset)
    else:
        query_set = AssessmentRAQuestionStatement.objects.filter(
            ra_question=ra_question_id).order_by('hazard')
        formset = RAQuestionStatmentFormSet(queryset=query_set)
        set_ra_statements_hidden_fields(formset, files_to_show)
        #set_ra_statements_readonly_fields(formset)
    formset.is_valid()

    return render_to_response("crptapp/question_detail.html", {
        "formset": formset,
        "description": question_statement.ra_question.description,
        "assessment": assessment,
        "ra_section": ra_section,
    },
                              context_instance=RequestContext(request))
Пример #37
0
        label='Select a fruit (AutoCompleteSelectMultipleField with combobox)',
        required=False,
        widget=selectable.AutoComboboxSelectMultipleWidget)


class ChainedForm(forms.Form):
    city = selectable.AutoCompleteSelectField(
        lookup_class=CityLookup,
        label='City',
        required=False,
        widget=selectable.AutoComboboxSelectWidget)
    state = USStateField(widget=USStateSelect, required=False)


class FarmForm(forms.ModelForm):
    class Meta(object):
        model = Farm
        widgets = {
            'fruit':
            selectable.AutoCompleteSelectMultipleWidget(
                lookup_class=FruitLookup),
        }
        fields = (
            'name',
            'owner',
            'fruit',
        )


FarmFormset = modelformset_factory(Farm, FarmForm)
Пример #38
0
class CreateUpdateEmailTemplateForm(ModelForm):
    """
    Form used for creating and updating email templates.
    """
    id = forms.IntegerField(label=_('Template ID'), required=False)
    variables = forms.ChoiceField(label=_('Insert variable'), choices=[['', 'Select a category']], required=False)
    values = forms.ChoiceField(label=_('Insert value'), choices=[['', 'Select a variable']], required=False)
    folder = forms.ModelChoiceField(
        label=_('Folder'),
        queryset=EmailTemplateFolder.objects,
        empty_label=_('Choose a folder'),
        required=False
    )

    attachments = FormSetField(
        queryset=EmailTemplateAttachment.objects,
        formset_class=modelformset_factory(EmailTemplateAttachment, form=AttachmentBaseForm, can_delete=True, extra=0),
        template='email/formset_template_attachment.html'
    )

    def __init__(self, *args, **kwargs):
        """
        Overload super().__init__ to change the appearance of the form and add parameter fields if necessary.
        """
        self.draft_id = kwargs.pop('draft_id', None)
        self.message_type = kwargs.pop('message_type', 'reply')
        super(CreateUpdateEmailTemplateForm, self).__init__(*args, **kwargs)

        email_parameter_choices = get_email_parameter_choices()
        self.fields['variables'].choices += [[x, x] for x in email_parameter_choices.keys()]
        self.fields['variables'].choices.append(['Custom variables', 'Custom variables'])

        self.fields['folder'].queryset = EmailTemplateFolder.objects.order_by('name')

        for value in email_parameter_choices:
            for val in email_parameter_choices[value]:
                self.fields['values'].choices += [[val, email_parameter_choices[value][val]], ]

        # Add custom variables to choices
        queryset = TemplateVariable.objects.all().filter(Q(is_public=True) | Q(owner=get_current_user()))

        for template_variable in queryset:
            custom_variable_name = 'custom.' + template_variable.name.lower()

            if template_variable.is_public:
                custom_variable_name += '.public'

            self.fields['values'].choices += [[custom_variable_name, template_variable.name], ]

        if self.instance and self.instance.pk:
            self.fields['id'].widget.attrs['readonly'] = True

        self.fields['attachments'].initial = EmailTemplateAttachment.objects.filter(template_id=self.instance.id)

    def clean(self):
        """
        Make sure the form is valid.
        """
        cleaned_data = super(CreateUpdateEmailTemplateForm, self).clean()
        html_part = cleaned_data.get('body_html')
        text_part = cleaned_data.get('body_text')

        if not html_part and not text_part:
            self._errors['body_html'] = self.error_class(
                [_('Please fill in the html part or the text part, at least one of these is required.')]
            )
        elif html_part:
            # For some reason sometimes nbsp's are added, so remove them
            parsed_template = TemplateParser(self.clean_nbsp(html_part))

            if parsed_template.is_valid():
                cleaned_data.update({
                    'body_html': parsed_template.get_text(),
                })
            else:
                self._errors['body_html'] = parsed_template.error.message
                del cleaned_data['body_html']
        elif text_part:
            # For some reason sometimes nbsp's are added, so remove them
            parsed_template = TemplateParser(self.clean_nbsp(text_part))
            if parsed_template.is_valid():
                cleaned_data.update({
                    'body_text': parsed_template.get_text(),
                })
            else:
                self._errors['body_text'] = parsed_template.error.message
                del cleaned_data['body_text']

        return cleaned_data

    def clean_nbsp(self, text):
        variable_regex = '\[\[&nbsp.+\]\]'
        # Get all template variables that contain an &nbsp;
        search_result = re.findall(variable_regex, text)

        if search_result:
            for template_variable in search_result:
                # Change the nbsp to an actual space
                replace_variable = template_variable.replace('&nbsp;', ' ')
                # Replace the variable in the actual text
                text = re.sub(variable_regex, replace_variable, text)

        return text

    def save(self, commit=True):
        instance = super(CreateUpdateEmailTemplateForm, self).save(False)
        instance.body_html = linebreaksbr(instance.body_html.strip(), autoescape=False)

        if commit:
            instance.save()

        for attachment_form in self.cleaned_data.get('attachments'):
            attachment = attachment_form.cleaned_data.get('attachment', None)

            if attachment:
                if isinstance(attachment, FieldFile) and attachment_form.cleaned_data.get('DELETE'):
                    # We can only delete attachments that exist, so check if it's a new file or an existing file
                    attachment_form.instance.attachment.delete(save=False)
                    attachment_form.instance.delete()
                elif not attachment_form.cleaned_data.get('DELETE'):
                    # If we're not deleting the attachment we can just save it
                    attachment = attachment_form.save(commit=False)
                    attachment.template = instance
                    attachment.save()

        return instance

    def is_multipart(self):
        """
        Return True since file uploads are possible.
        """
        return True

    class Meta:
        model = EmailTemplate
        fields = ('id', 'name', 'subject', 'folder', 'variables', 'values', 'body_html', 'attachments')
        widgets = {
            'values': forms.Select(attrs={
                'disabled': 'disabled',
            }),
            'body_html': Wysihtml5Input(attrs={
                'container_class': 'email-template-body'
            }),
        }
Пример #39
0
def get_related_forms(model, form_data=None, db_object=None, model_history=[]):
    '''
    Given a model and optionally a data source from a form or object
    will return all the related forms for that model, tracing relations
    specified in the models add_related property.
    
    if form_data or a db_object are specified will in that order of precedence 
    use them to populate field_data (see below) so that a form can initialize 
    forms with data.

    Returns a list of generic forms each of which is:
        a standard Django empty form for the related model
        a standard Django management form for the related model (just four hidden inputs that 
                    report the number of items in a formset really)
        a dictionary of field data, which has for each field a list of values one for each 
                    related object (each list is the same length, 1 item for each related object)

        The data source for field_data can be 
            form_data (typically a QueryDict from a request.POST or request.GET) or 
            a database object (being the instance of a Model)
        If no data source is specified, then only the empty and management forms are included, 
        the dictionary of field data is not.
        
    model_history is used to avoid infinite recursion. When calling itself pushes the model onto model_history, and 
    on entering checks if model is in model_history, bailing if so.
    '''    
    def custom_field_callback(field):
        '''A place from which to deliver a customised formfield for a given field'''
        return field.formfield()

    assert not model in model_history, "Model Error: You have defined a recursive set of model relations with the model.add_related attribute."

    # This funcion is recursive, and searches for related forms in related forms in related forms ...
    # So we track the depth of the recursion here and keep a history so as to try and avoid endless loops.  
    model_depth = len(model_history)
    debug_prefix = '\t' * model_depth 
            
    print_debug(f"\n{debug_prefix}=================================================================")
    print_debug(f"{debug_prefix}Starting get_related_forms({model._meta.object_name}), history={[m._meta.object_name for m in model_history]}")

    # A db_object if supplied must be an instance of the specified model     
    if not db_object is None:
        assert isinstance(db_object, model), "Coding Error: db_object must be an instance of the specified model"

    if not form_data is None:
        print_debug(f"{debug_prefix}Using form_data:")
        for (key, val) in form_data.items():
            print_debug(f"{debug_prefix}\t{key}:{val}")
        print_debug("\n")            
    elif not db_object is None:
        print_debug(f"{debug_prefix}Using db_object: {db_object._meta.object_name} {db_object.pk}")

    related_forms = collections.OrderedDict()

    print_debug(f"{debug_prefix}Looking for {len(add_related(model))} related forms: {add_related(model)}.")

    relations = [f for f in model._meta.get_fields() if (f.is_relation)]
    if len(relations) > 0:
        for relation in relations:
            # These are the relations we can expect:
            #     many_to_many:  this is a ManyToManyField
            #     many_to_one:   this is a ForeignKey field
            #     one_to_many    this is an _set field (i.e. has a ForeignKey in another model pointing to this model and this field is the RelatedManager)
            #     one_to_one:    this is a OneToOneField
            #
            # At this point we have a model, and a list of relations (other models that relate to it)
            # For a given relation there will be one or more related objects. If the relation is of the
            # form ToOne there will be one related object. If the relation is of the form ToMany there will 
            # be many related objects. 
            #
            # For this relation we want a "related_form" which we'll provide as a empty_form
            # and if a data source is provided (form_data or db_object), to that empty_form  
            # we want to add an attribute "field_data" which has for each field in the empty form 
            # a list of values for each instance. 
            #
            # For completeness we also add instance_forms to the empty form which is a dictionary of forms
            # keyed on the PK of the individual instances (that are listed in field_data) and the value
            # is a form for that instance (essentially the empty_form with values in the fields).
            #
            # The value in field_data might itself be a simple scalar (for ordinary fields), or a PK if 
            # the field is a _to_one relation (a relation pointing to one object of another model, or a list of
            # PKs if the field is a _to_many relation (a relation pointing to many objects in another model).  
            #
            # This is a proxy for a related_formset in a way. The related_form is an empty_form, a pro
            # forma for one form in the formset and field_data contains for each field in the related model a 
            # list of values, one for each form in the formset from which a web page can, in javascript, create
            # the individual forms in the formset with populated values. 
            #
            # To reiterate:
            #
            # There is one field_data for each related model, and it is dictionary which is keyed on the 
            # related model's field name(s). The value will depend on whether the relation is to one or many 
            # other objects (i.e. contain a value or a list). 
            #
            # The field in the related_model can itself be:
            #    a value    - in which case the item added to a field_data list is a value
            #    a relation to one related object - in which case the item added to a field_data list is a PK
            #    a relation to many related objects - in which case the item added to a field_data list is a list of PKs
            #
            # So field_data for a given field could be a list of lists all depending on the relationships.
            #
            # This is recursive, in that the related_form may also be given an attribute "related_forms" which is
            # a dictionary of related forms in the self same manner for that related model. 
            # 
            # For added convenience, the fields in each related model are also included in field_data.
            # They are included as lists of values (one for each instance) with pseudo field names in form
            # model__field (using django's double underscore convention). This is complicated and a good
            # working example will be useful
            #
            # To include a relation it has to be identified in a model's add_related attribute.
            # Either this object has a field which is specified in its add_related list, or
            # The related model has a field which is specified in add_related (in the format "model.field")
            # The relation will have an attribute named "field" if it's a candidate for the latter. 
            # That "field" in the relation is the field in the related model which points to this one.
            #
            # Examples to elucidate:
            #
            # 1) If we have a Team model and object there is a related model Member which has a field 
            # named "team" which is a ForeignKey field pointing team, then this is many_to_one relationship 
            # (many Members per Team), then the Team model we should have an attribute add_related = ['Member.team']
            # to request that we include the related form for Member. There is no field in Team for the relationship
            # for us to specify! But if the team field in Member has a related_name ('members' for example) a field of 
            # that name is created in Team and so we also can request the related form with  add_related = ['members'].
            # Both methods are supported here.
            #
            # 2) If on the other hand a Member can be in multiple Teams, then we have a many_to_many relationship. This
            # could be via a ManyToMany field in Team called "members", and if so to include the related form for Member
            # we would specify add_related = ['members'].
            #
            # In case 2) the name of the relation will be 'members' and this is what we can look for in add_related(model)
            # In case 1) the name of the relation will be the related_name that was specified for the team field in Member,
            # and the relation will have a field that is the field in Member that is pointing to Team. In this example
            # a field 'team' that points to Team and so Member.team is also a way to specify this related form if desired.
            
            # If the model's add_related field mentions this relation ... and only if.
            if ( relation.name in add_related(model)
                or (hasattr(relation, "field") 
                and relation.field.model.__name__ + "." + relation.field.name in add_related(model)) ):
                
                # Build the class for the related formset. The related formset will be an instance of this class 
                Related_Formset = modelformset_factory(relation.related_model, can_delete=False, extra=0, fields=('__all__'), formfield_callback=custom_field_callback)
                related_formset = None # Will be built using either form_data or db_object as a data source 

                # By default, we have no management form. One comes into being if we succeed in
                # populating a formset with form_data or from a db_object.  
                has_management_form = False
                
                # ==============================================================
                # Build the related_formset and field_data for this relation
                
                # Try to use form_data if it's present (it may fail as the form_data may not include
                # a submission for the related model). We record success or failure in found_form_data  
                # so we can look at db_object for field values.
                found_form_data = False
                if not form_data is None:
                    related_formset = get_formset_from_request(Related_Formset, form_data)
                    if hasattr(related_formset, "field_data") and related_formset.field_data:
                        found_form_data = True

                # If no form data was found try and find it in the db_object
                if not found_form_data and not db_object is None:                    
                    print_debug(f"{debug_prefix}Getting formset from: {db_object._meta.object_name} {db_object.pk} using relation {relation} through the field {relation.name}.")
                    related_formset = get_formset_from_object(Related_Formset, db_object, relation)

                # If no management form is present this will fail with a ValidationError
                # Catch this fact here quietly, for compatibility with the 'add' 
                # approach, and ease of saving it later (the management form that is)
                try:
                    has_management_form = hasattr(related_formset, 'management_form')
                except ValidationError as e:
                    if e.code == "missing_management_form":
                        has_management_form = False
                    
                # If we didn't succeed in building a formset from form_data or a db_object just
                # build one from the model, for the empty_form including a management form,
                if not has_management_form:
                    related_formset = Related_Formset(prefix=relation.related_model.__name__)
                
                # Add the name of the field/relation to the related form.
                # We want to know this when saving related to check the field properties.
                related_formset.field_name = relation.name 

                # Build the generic_related_form for this relation and save it
                model_name = relation.related_model.__name__
                related_forms[model_name] = generic_related_form(related_formset)

    print_debug(f"{debug_prefix}Found {len(related_forms)} related forms: {[f[0] for f in related_forms.items()]}.")

    # Now add an instance form for each instance that we find in the field_data
    # and for each instance form, look for related forms in turn, walking down the 
    # tree so to speak. 
    for rf in related_forms:
        rm = related_forms[rf].Meta.model
        
        print_debug(f"\n{debug_prefix}Processing {rm._meta.object_name}: add_related={add_related(rm)} ")
        
        # add generic related forms (with no object) to provide easy access to 
        # the related empty form and field widgets in the context. Instance forms
        # are added later for each related object. 
        if add_related(rm):
            related_forms[rf].related_forms = get_related_forms(rm, model_history=model_history+[model])
            print_debug(f"{debug_prefix}Got {len(related_forms[rf].related_forms)} generic forms related to {rm._meta.object_name}: {list(related_forms[rf].related_forms.keys())}")
        
            # add instance_forms for each instance (of the related form)
            if hasattr(related_forms[rf], "field_data") and rm._meta.pk.attname in related_forms[rf].field_data:
                related_forms[rf].instance_forms = {}
    
                # Ordering is important here as field_data which are lists are in an order and should all be in the same order
                # So we need to observe and respect the order of pk values in field_data when creating instance lists of related values
                pk_list = []                   # Keep an ordered list of the PKs as the dictionary "instance_forms" loses order
                pk_attr = rm._meta.pk.attname  # Get the name of the primary key attribute
    
                # Create the instance_forms, that is one related_forms object per related instance  
                pk_placeholder = 0
                
                # To loop easily, we need a list of pks 
                # but it may be in field_data as a single pk not a list so build a list if it's not a list.
                pks = related_forms[rf].field_data[pk_attr]
                pks = pks if isinstance(pks, list) else [pks] 
                print_debug(f"{debug_prefix}Processing {rm._meta.object_name}: instance PKs={pks}")
    
                for pk in pks:
                    if pk is None:
                        ph = 'PK_{}'.format(pk_placeholder)
                        pk_placeholder += 1
                        print_debug(f"{debug_prefix}{rm._meta.object_name} PK=None so using a placeholder PK={ph}")
                    else:
                        ph = pk
                        print_debug(f"{debug_prefix}{rm._meta.object_name} PK={ph}")
                    pk_list.append(ph)
                                                            
                    if not pk is None:
                        o = rm.objects.get(pk=pk)
                        print_debug(f"{debug_prefix}{rm._meta.object_name} PK={ph}. Got object from DB: {o}")
                    else:
                        i = len(pk_list)-1
                        fields = {}
                        print_debug(f"{debug_prefix}{rm._meta.object_name} PK={ph}. Checking field_data : {related_forms[rf].field_data.items()}")                    
                        for field, values in related_forms[rf].field_data.items():
                            f = rm._meta.get_field(field)
                            print_debug(f"{debug_prefix}{rm._meta.object_name} PK={ph}. Checking field: {field}, i: {i}, values[i]: {values[i]}, f: {f}, f.is_relation: {f.is_relation}")
                            if values[i] is None:
                                val = None
                            elif f.is_relation:
                                m = f.related_model
                                print_debug(f"{debug_prefix}{rm._meta.object_name} PK={ph}. related_model: {m}, one_to_one: {f.one_to_one}, many_to_one: {f.many_to_one}, one_to_many: {f.one_to_many}, many_to_many: {f.many_to_many}")
                                if f.one_to_one or f.many_to_one:
                                    val = m.objects.get(pk=values[i])
                                elif f.one_to_many or f.many_to_many:
                                    # TODO: Test this, could fail, untested code!
                                    val = m.objects.filter(pk__in=values[i]) 
                            else:
                                val = values[i]
                            
                            # I know this bombs when a many_to_many field with val None is added to fields
                            # TODO: Check this works for many_to_many fields when val is not None! 
                            # To do this edit a team play session and put a break here on save. Should land
                            # here with a many to many with a val.   
                            if not ((f.one_to_many or f.many_to_many) and val is None):    
                                fields[field] = val
                            
                        print_debug("{debug_prefix}{rm._meta.object_name} PK={ph}. Building object from field_data : {fields}")
                        o = rm(**fields)
                        print_debug("{debug_prefix}{rm._meta.object_name} PK={ph}. Built object from field_data : {o}")
                    
                    # Earlier we added a generic empty related form, now we add a specific one for each instance populated with
                    # data avalable.
                    instance_forms = get_related_forms(rm, form_data=form_data, db_object=o, model_history=model_history+[model])
                    instance_forms.object = o
                    
                    if not instance_forms is None:               
                        print_debug(f"{debug_prefix}{rm._meta.object_name} PK={ph}. Got {len(instance_forms)} related instance forms: {list(instance_forms.keys())}.")
                        related_forms[rf].instance_forms[ph] = instance_forms
                            
            # Finally, for ease of use in the template context 
            # add field_data for all the instance related fields as well
            # TODO: Why do we populate field_data only for Player not for Rank?
            if hasattr(related_forms[rf],"instance_forms"):
                print_debug(f"{debug_prefix}Building field_data for model={rm._meta.object_name}, PKs={pk_list}")
                for pk in pk_list: # Walk the ordered list of PKs
                    print_debug(f"{debug_prefix}Found {len(related_forms[rf].instance_forms[pk])} instance forms: {list(related_forms[rf].instance_forms[pk].keys())} related to {rf} PK={pk}")
                    for form in related_forms[rf].instance_forms[pk]:
                        if hasattr(related_forms[rf].instance_forms[pk][form], "field_data") and len(related_forms[rf].instance_forms[pk][form].field_data) > 0:
                            print_debug(f"{debug_prefix}Adding field data to instance form of model={form} related to {rf} PK={pk}")
                            for ro_field in related_forms[rf].instance_forms[pk][form].field_data:
                                ro_field_name = form + "__" + ro_field
                                ro_field_value = related_forms[rf].instance_forms[pk][form].field_data[ro_field]
                                if not ro_field_name in related_forms[rf].field_data:
                                    related_forms[rf].field_data[ro_field_name] = []
                                related_forms[rf].field_data[ro_field_name].append(ro_field_value)
                                print_debug("f{debug_prefix}Added {ro_field_name}={ro_field_value}")                           
        else:
            print_debug(f"{debug_prefix}No related forms to build.")
            
    print_debug(f"{debug_prefix}Done with get_related_forms({model._meta.object_name})")
    print_debug(f"{debug_prefix}=================================================================\n")
    return related_forms            
Пример #40
0
        model = Attachment
        fields = [
            'file',
            'comment',
        ]


class BaseAttachmentFormset(BaseModelFormSet):
    """ Base class allowing to define forum attachment formsets. """
    def __init__(self, *args, **kwargs):
        self.post = kwargs.pop('post', None)
        super().__init__(*args, **kwargs)

    def save(self, commit=True, **kwargs):
        """ Saves the considered instances. """
        if self.post:
            for form in self.forms:
                form.instance.post = self.post
        super().save(commit)


AttachmentFormset = modelformset_factory(
    Attachment,
    AttachmentForm,
    formset=BaseAttachmentFormset,
    can_delete=True,
    extra=1,
    max_num=machina_settings.ATTACHMENT_MAX_FILES_PER_POST,
    validate_max=True,
)
Пример #41
0
                               required=False,
                               initial=0,
                               widget=forms.RadioSelect())

    class Meta:
        model = Rating
        fields = ('action', )


class BaseRatingFlagFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(BaseRatingFlagFormSet, self).__init__(*args, **kwargs)

    def save(self):
        for form in self.forms:
            if form.cleaned_data and user_can_delete_rating(
                    self.request, form.instance):
                action = int(form.cleaned_data['action'])

                if action == ratings.REVIEW_MODERATE_DELETE:
                    form.instance.delete(user_responsible=self.request.user)
                elif action == ratings.REVIEW_MODERATE_KEEP:
                    form.instance.approve(user=self.request.user)


RatingFlagFormSet = modelformset_factory(Rating,
                                         extra=0,
                                         form=ModerateRatingFlagForm,
                                         formset=BaseRatingFlagFormSet)
Пример #42
0
    def _get_formset(self, name, form, extra=None, initial=None, can_delete=True, \
                     update_button=None, fk_name=None, duplicate=False, \
                     exclude_from_duplication=None, queryset=None, allowed_objects=None, \
                     *args, **kwargs):

        def shift_keys(data, prefix, idx, has_file=False):
            if not data:
                return
            start = re.compile(r"^%s\-(?P<form_idx>\d+)\-(?P<suffix>.*)$" % prefix)
            if has_file:
                if (len(data.keys()) > 0):
                    data_sorted = sorted(data.keys())
                    first_form_key = data_sorted[0]
                    last_form_key = data_sorted[-1]
                    regex = start.match(first_form_key)
                    regex_dict = regex.groupdict()

                    form_idx = int(regex_dict['form_idx'])
                    if form_idx > 0:
                        previous_form_key = "%s-%d-%s" % (
                            prefix,
                            form_idx - 1,
                            regex_dict['suffix'],
                        )
                        if not data.has_key(previous_form_key):
                            data.setlist(previous_form_key, data.getlist(last_form_key))

            for key in sorted(data.keys()):
                regex = start.match(key)

                if regex is None:
                    continue

                regex_dict = regex.groupdict()
                form_idx = int(regex_dict['form_idx'])

                if form_idx < idx:
                    continue

                suffix = regex_dict['suffix']

                next_form_key = "%s-%d-%s" % (
                    prefix,
                    form_idx + 1,
                    suffix,
                )
                if data.has_key(next_form_key):
                    data.setlist(key, data.getlist(next_form_key))
                else:
                    del data[key]


        def resolve_callable(var, args=None, kwargs=None, default=None):
            if args is None:
                args = []

            if kwargs is None:
                kwargs = {}

            if callable(var):
                return var(*args, **kwargs) or default
            else:
                return var or default

        data = self.data.keys() and self.data.copy() or None
        files = self.files.keys() and self.files.copy() or None

        self.full_clean()

        prefix = self.get_formset_prefix(name) # calculates formset's prefix

        if self.is_valid():
            instance = self.save(commit=False)
        else:
            instance = self.instance
        field = self.get_related_field(name)
        to = self.get_related_model(name)

        form = resolve_callable(form, args=[instance])
        extra = resolve_callable(extra, args=[instance], default=0)
        queryset = resolve_callable(queryset, args=[instance])
        update_button = resolve_callable(update_button, args=[self.prefix])

        instance_pk = form._meta.model._meta.pk.name

        if data and prefix:
            for key in data.keys():
                if not key.startswith(prefix):
                    del data[key]
            if not data.keys():
                data = None

            if files is not None:
                for key in files.keys():
                    if not key.startswith(prefix):
                        del files[key]
                if not files:
                    files = None

        if data:
            # Asking to delete last form
            if isinstance(data, QueryDict):
                nb_forms = [int(total_form_count) for total_form_count in data.getlist("%s-%s" % (prefix, TOTAL_FORM_COUNT))]
            else:
                nb_forms = [ int(data["%s-%s" % (prefix, TOTAL_FORM_COUNT)]) ]

            if len(nb_forms) > 1:
                data["%s-%s" % (prefix, TOTAL_FORM_COUNT)] = max(nb_forms)

                if duplicate:
                    last_index = max(nb_forms) - 1

                    start = "%s-%d-" % (prefix, last_index - 1)
                    for key, value in data.iteritems():
                        if key == "%s%s" % (start, instance_pk) or key == "%s%s" % (start, INITIAL_FORM_COUNT):
                            continue

                        cont = False

                        if exclude_from_duplication:
                            for k in exclude_from_duplication:
                                exclude_key = resolve_callable(k, args=[start])
                                if exclude_key[-1] == '-' and key.startswith(exclude_key) or re.match(exclude_key, key):
                                    cont = True
                        if cont:
                            continue

                        if key.startswith(start) and not key.endswith("-%s" % instance_pk):
                            if key.endswith(INITIAL_FORM_COUNT):
                                value = 0
                            new_line = {
                                "%s-%d-%s" % (prefix, last_index, key[len(start):]): value
                            }
                            data.update(new_line)

            if to:
                i = 0
                for _ in range(int(data.get("%s-%s" % (prefix, TOTAL_FORM_COUNT), 0))):
                    pk_key = "%s-%d-%s" % (prefix, i, instance_pk)

                    if i >= int(data["%s-%s" % (prefix, INITIAL_FORM_COUNT)]):
                        i += 1
                        continue

                    pk = data.get(pk_key, 0)
                    pk = str(pk).isdigit() and int(pk) or 0

                    try:
                        to.objects.get(pk = pk)
                    except to.DoesNotExist:
                        shift_keys(data, prefix, i)
                        shift_keys(files, prefix, i)
                        data["%s-%s" % (prefix, TOTAL_FORM_COUNT)] = int(data["%s-%s" % (prefix, TOTAL_FORM_COUNT)]) - 1
                        data["%s-%s" % (prefix, INITIAL_FORM_COUNT)] = int(data["%s-%s" % (prefix, INITIAL_FORM_COUNT)]) - 1
                    else:
                        i += 1

            # Updates form's data with initial data
            if update_button and data.has_key(update_button):
                initial = resolve_callable(initial, args=[instance], default=[])
                for i, pair in enumerate(initial):
                    prefix_ = "%s-%d-" % (prefix, i)

                    map(data.__delitem__, filter(lambda k: k.startswith(prefix_), data.keys()))

                    for key, value in pair.items():
                        name_ = "%s%s" % (prefix_, key)
                        data[name_] = unicode(value)
                if instance.pk:
                    getattr(instance, name).all().delete()

                data.update({ "%s-%s" % (self.add_prefix(name), INITIAL_FORM_COUNT): 0 })
                data.update({ "%s-%s" % (self.add_prefix(name), TOTAL_FORM_COUNT): len(initial) })

            # Deletes a nested form
            if prefix not in self.safe_delete:
                for i in range(int(data.get("%s-%s" % (prefix, TOTAL_FORM_COUNT), 0)))[::-1]:
                    base_key = "%s-%d-" % (prefix, i)

                    if "%s%s" % (base_key, DELETION_FIELD_NAME) in data.keys():
                        objects_deleted = False
                        if to:
                            objects = to.objects.filter(pk = data.get("%s%s" % (base_key, instance_pk)) or 0)
                            if objects.exists():
                                objects_deleted = True
                                for obj in objects:
                                    obj.delete()

                        shift_keys(data, prefix, i)
                        shift_keys(files, prefix, i, True)
                        data["%s-%s" % (prefix, TOTAL_FORM_COUNT)] = int(data["%s-%s" % (prefix, TOTAL_FORM_COUNT)]) - 1
                        if objects_deleted:
                            data["%s-%s" % (prefix, INITIAL_FORM_COUNT)] = int(data["%s-%s" % (prefix, INITIAL_FORM_COUNT)]) - 1

            if "%s-%s" % (prefix, TOTAL_FORM_COUNT) not in data.keys():
                data = files = None

            initial = None
        elif not self.instance.pk:
            initial = resolve_callable(initial, args=[instance], default=[])

        formset = None

        #print prefix, "%s-%s" % (prefix, TOTAL_FORM_COUNT), data and data.get("%s-%s" % (prefix, TOTAL_FORM_COUNT), "NOT SET")
        #print prefix, "%s-%s" % (prefix, INITIAL_FORM_COUNT), data and data.get("%s-%s" % (prefix, INITIAL_FORM_COUNT), "NOT SET")

        if instance.pk:
            if isinstance(field, RelatedObject):
                if not queryset or not isinstance(queryset, QuerySet):
                    queryset = getattr(self.instance, name).all()

                formset_class = inlineformset_factory(
                    instance.__class__,
                    to,
                    form,
                    ComplexBaseInlineFormSet,
                    extra = extra,
                    formfield_callback = lambda f, **kwargs: f.formfield(**kwargs),
                    fk_name = fk_name,
                )
                formset = formset_class(
                    data = data,
                    files = files,
                    prefix = prefix,
                    instance = instance,
                    queryset = queryset,
                )
            else:
                if not queryset or not isinstance(queryset, QuerySet):
                    queryset = getattr(self.instance, "_%s" % name, None)
                    if not queryset or not isinstance(queryset, QuerySet):
                        _data = data or {}
                        queryset = to.objects.filter(
                                pk__in = list(to.objects.filter(
                                    **{
                                        field.rel.related_name or field.related.var_name: self.instance.pk
                                    }
                                ).values_list("pk", flat=True)) + [
                                    _data.get('%s-%d-%s' % (prefix, x, instance_pk))
                                    for x in range(int(_data.get("%s-%s" % (prefix, INITIAL_FORM_COUNT), 0)))
                                ]
                        ).distinct()
                if isinstance(allowed_objects, QuerySet):
                    queryset = allowed_objects.filter(
                        pk__in = queryset.values_list('pk', flat=True)
                    ).distinct()

                formset_class = modelformset_factory(
                    to,
                    form,
                    extra = extra,
                    can_delete=can_delete,
                    formfield_callback = lambda f, **kwargs: f.formfield(**kwargs),
                )
                formset = formset_class(
                    data,
                    files,
                    prefix = prefix,
                    initial = not self.instance.pk and isinstance(initial, list) and initial or None,
                    queryset = queryset,
                )
        else:
            if data:
                _data = data or {}
                queryset = to.objects.filter(
                    pk__in = [
                        _data.get('%s-%d-%s' % (prefix, x, instance_pk))
                        for x in range(int(_data.get("%s-%s" % (prefix, INITIAL_FORM_COUNT), 0)))
                    ]
                ).distinct()
            else:
                queryset = to.objects.none()

            formset_class = modelformset_factory(
                to,
                form,
                extra=extra,
                can_delete=can_delete,
                formfield_callback = lambda f, **kwargs: f.formfield(**kwargs),
            )
            formset = formset_class(
                data,
                files,
                prefix = prefix,
                queryset = queryset,
                initial = not self.instance.pk and isinstance(initial, list) and initial or None,
            )


        if isinstance(field, RelatedObject):
            for form in formset.forms:
                setattr(form.instance, field.field.name, instance)

        try:
            deleted_instance_pks = [ f.instance.pk for f in formset.deleted_forms if f.instance ]
        except:
            deleted_instance_pks = []

        tmp_objs = []

        for form in formset.forms:
            try:
                if form.instance.pk not in deleted_instance_pks:
                    tmp_objs.append(form.instance)
            except Exception:
                pass

        setattr(instance, "_%s" % name, tmp_objs)

        return formset
Пример #43
0

class BaseFeaturedCollectionFormSet(BaseModelFormSet):

    def __init__(self, *args, **kw):
        super(BaseFeaturedCollectionFormSet, self).__init__(*args, **kw)
        for form in self.initial_forms:
            try:
                form.initial['collection'] = (FeaturedCollection.objects
                    .get(id=form.instance.id).collection.id)
            except (FeaturedCollection.DoesNotExist, Collection.DoesNotExist):
                form.initial['collection'] = None


FeaturedCollectionFormSet = modelformset_factory(FeaturedCollection,
    form=FeaturedCollectionForm, formset=BaseFeaturedCollectionFormSet,
    can_delete=True, extra=0)


class OAuthConsumerForm(happyforms.ModelForm):

    class Meta:
        model = Consumer
        fields = ['name', 'description', 'status']


class MonthlyPickForm(happyforms.ModelForm):
    image = forms.CharField(required=False)
    blurb = forms.CharField(max_length=200,
                            widget=forms.Textarea(attrs={'cols': 20,
                                                         'rows': 2}))
Пример #44
0
class ComposeEmailForm(FormSetFormMixin, forms.Form):
    """
    Form for writing an EmailMessage as a draft, reply or forwarded message.
    """
    draft_pk = forms.IntegerField(widget=forms.HiddenInput(), required=False)

    template = forms.ModelChoiceField(
        label=_('Template'),
        queryset=EmailTemplate.objects,
        empty_label=_('Choose a template'),
        required=False
    )

    send_from = forms.ChoiceField()

    send_to_normal = TagsField(
        label=_('To'),
        widget=AjaxSelect2Widget(
            attrs={
                'class': 'tags-ajax'
            },
            url=reverse_lazy('search_view'),
            model=Contact,
            filter_on='contacts_contact',
        ),
    )
    send_to_cc = TagsField(
        label=_('Cc'),
        required=False,
        widget=AjaxSelect2Widget(
            attrs={
                'class': 'tags-ajax'
            },
            url=reverse_lazy('search_view'),
            model=Contact,
            filter_on='contacts_contact',
        ),
    )
    send_to_bcc = TagsField(
        label=_('Bcc'),
        required=False,
        widget=AjaxSelect2Widget(
            attrs={
                'class': 'tags-ajax'
            },
            url=reverse_lazy('search_view'),
            model=Contact,
            filter_on='contacts_contact',
        ),
    )

    attachments = FormSetField(
        queryset=EmailOutboxAttachment.objects,
        formset_class=modelformset_factory(EmailOutboxAttachment, form=AttachmentBaseForm, can_delete=True, extra=0),
        template='email/formset_attachment.html',
    )

    subject = forms.CharField(required=False, max_length=255)
    body_html = forms.CharField(widget=Wysihtml5Input(), required=False)

    def __init__(self, *args, **kwargs):
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        # Only show the checkbox for existing attachments if we have a pk and if we forward.
        if 'initial' in kwargs and 'draft_pk' in kwargs['initial'] and self.message_type == 'forward':
            existing_attachment_list = EmailAttachment.objects.filter(
                message_id=kwargs['initial']['draft_pk'],
                inline=False
            )
            choices = [(attachment.id, attachment.name) for attachment in existing_attachment_list]
            self.fields['existing_attachments'] = forms.MultipleChoiceField(
                choices=choices,
                widget=forms.CheckboxSelectMultiple,
                initial=[a.id for a in existing_attachment_list],
                required=False,
            )

        self.fields['template'].queryset = EmailTemplate.objects.order_by('name')

        user = get_current_user()

        email_account_list = get_shared_email_accounts(user)

        self.email_accounts = email_account_list

        # Only provide choices you have access to
        self.fields['send_from'].choices = [(email_account.id, email_account) for email_account in self.email_accounts]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            if user.primary_email_account:
                initial_email_account = user.primary_email_account.id
            else:
                for email_account in self.email_accounts:
                    if email_account.email_address == user.email:
                        initial_email_account = email_account
                        break
        elif isinstance(initial_email_account, basestring):
            for email_account in self.email_accounts:
                if email_account.email == initial_email_account:
                    initial_email_account = email_account
                    break

        self.initial['send_from'] = initial_email_account

    def is_multipart(self):
        """
        Return True since file uploads are possible.
        """
        return True

    def clean(self):
        cleaned_data = super(ComposeEmailForm, self).clean()

        # Make sure at least one of the send_to_X fields is filled in when sending the email
        if 'submit-send' in self.data:
            if not any([cleaned_data.get('send_to_normal'), cleaned_data.get('send_to_cc'),
                        cleaned_data.get('send_to_bcc')]):
                self._errors['send_to_normal'] = self.error_class([_('Please provide at least one recipient.')])

        # Clean send_to addresses.
        cleaned_data['send_to_normal'] = self.format_recipients(cleaned_data.get('send_to_normal'))
        cleaned_data['send_to_cc'] = self.format_recipients(cleaned_data.get('send_to_cc'))
        cleaned_data['send_to_bcc'] = self.format_recipients(cleaned_data.get('send_to_bcc'))

        for recipient in self.cleaned_data['send_to_normal']:
            email = parseaddr(recipient)[1]
            validate_email(email)

        return cleaned_data

    def format_recipients(self, recipients):
        """
        Strips newlines and trailing spaces & commas from recipients.
        Args:
            recipients (str): The string that needs cleaning up.
        Returns:
            String of comma separated email addresses.
        """
        formatted_recipients = []
        for recipient in recipients:
            # Clean each part of the string
            formatted_recipients.append(recipient.rstrip(', ').strip())

        # Create one string from the parts
        formatted_recipients = ', '.join(formatted_recipients)

        # Regex to split a string by comma while ignoring commas in between quotes
        pattern = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''')

        # Split the single string into separate recipients
        formatted_recipients = pattern.split(formatted_recipients)[1::2]

        # It's possible that an extra space is added, so strip it
        formatted_recipients = [recipient.strip() for recipient in formatted_recipients]

        return formatted_recipients

    def clean_send_from(self):
        """
        Verify send_from is a valid account the user has access to.
        """
        cleaned_data = self.cleaned_data
        send_from = cleaned_data.get('send_from')

        try:
            send_from = int(send_from)
        except ValueError:
            pass
        else:
            try:
                send_from = self.email_accounts.get(pk=send_from)
            except EmailAccount.DoesNotExist:
                raise ValidationError(
                    _('Invalid email account selected to use as sender.'),
                    code='invalid',
                )
            else:
                return send_from

    class Meta:
        fields = (
            'draft_pk',
            'send_from',
            'send_to_normal',
            'send_to_cc',
            'send_to_bcc',
            'subject',
            'template',
            'body_html',
            'attachments',
        )
Пример #45
0
def multi_save_lines(request, document_id):
    get_for_ct = ContentType.objects.get_for_model
    b_entity = get_object_or_404(
        CremeEntity.objects.select_for_update(),
        pk=document_id,
        entity_type__in=[get_for_ct(c) for c in BILLING_MODELS],
    ).get_real_entity()

    user = request.user
    user.has_perm_to_change_or_die(b_entity)

    formset_to_save = []
    errors = []

    class _LineForm(line_forms.LineEditForm):
        def __init__(self, *args, **kwargs):
            self.empty_permitted = False
            super().__init__(user=user,
                             related_document=b_entity,
                             *args,
                             **kwargs)

    # Only modified formsets land here
    for line_ct_id, data in request.POST.items():
        line_model = get_ct_or_404(line_ct_id).model_class()

        prefix = LINE_FORMSET_PREFIX.get(line_model)
        if prefix is None:
            raise ConflictError('Invalid model (not a line ?!)')

        qs = line_model.objects.filter(
            relations__object_entity=b_entity.id,
            relations__type=constants.REL_OBJ_HAS_LINE,
        )

        lineformset_class = modelformset_factory(line_model,
                                                 form=_LineForm,
                                                 extra=0,
                                                 can_delete=True)
        lineformset = lineformset_class(jsonloads(data),
                                        prefix=prefix,
                                        queryset=qs)

        if lineformset.is_valid():
            formset_to_save.append(lineformset)
        else:
            get_field = line_model._meta.get_field

            for form in lineformset:
                if form.errors:
                    instance = form.instance
                    item = None

                    if instance.pk:
                        # We retrieve the line again because the field 'on_the_fly_item' may have been cleaned
                        # TODO: avoid this query (API for field modifications -- see HistoryLine)
                        item = line_model.objects.get(
                            pk=instance.pk
                        ).on_the_fly_item or instance.related_item

                    errors.append({
                        'item':
                        item,
                        'instance':
                        instance,
                        'errors': [(
                            None if field == '__all__' else get_field(field),
                            msg,
                        ) for field, msg in form.errors.items()],
                    })

    if errors:
        return render(request,
                      'billing/frags/lines-errors.html',
                      context={'errors': errors},
                      status=409)

    # Save all formset now that we haven't detect any errors
    for formset in formset_to_save:
        formset.save()

    return HttpResponse()
Пример #46
0






class PlacePriceForm(ModelForm):
    currency = ModelChoiceField(Currency.objects.filter(active=True), empty_label=None, label=_('Currency'))
    extra_limit = ChoiceField(choices=NO_OF_BEDS,label=_('Extra charge for more guests than'))
    class Meta:
        model=Place
        fields = ('price','currency','weekend_price','weekly_discount','monthly_discount','extra_limit','extra_price','cleaning_fee')

from django.forms.models import modelformset_factory
SPFormSet = modelformset_factory(SessionalPrice, extra=2,  exclude=('place','active'),can_delete =True)

@login_required
def edit_prices(request, id):
    lang = request.LANGUAGE_CODE
    user = request.user
    place = Place.objects.get(pk=id, owner=user)
    if request.method == 'POST':
        form = PlacePriceForm(request.POST,instance=place)
        spset = SPFormSet(request.POST, queryset=SessionalPrice.objects.filter(place=place))

        if spset.is_valid():
            spset = spset.save(commit=False)
            for f in spset:
                f.place = place
                f.save()
Пример #47
0
            # if (cd.get('amount') % cd.get('contract').tier.fee) != 0:
            # 	self._errors['amount'] = self.error_class(
            # 		[_('Payment amount ($%s) is not a clean multiple of '
            # 		   'Contract Fee ($%s)' % (cd.get('amount'),
            # 		                           cd.get('contract').tier.fee))])

        return cd


class PaymentForm(PaymentFormAdmin):
    class Meta:
        model = Payment
        exclude = ['user',
                   'verified']  # Hide the 'verified' field from the User

    def __init__(self, by_user=None, *args, **kwargs):
        super(PaymentForm, self).__init__(*args, **kwargs)

        self.fields['date_paid'].widget = widgets.AdminDateWidget()

        if by_user is not None:
            self.fields['contract'] = forms.ModelChoiceField(
             queryset=Contract.objects \
              .filter(user__username=by_user) \
              .exclude(status='TER') \
              .order_by('-start'),
             empty_label=None)


PaymentFormAdminFormset = modelformset_factory(Payment, extra=0)
Пример #48
0
def attachment_formset_factory():
    return modelformset_factory(DocumentAttachment,
                                form=AttachmentForm,
                                extra=1)
Пример #49
0
from ._utils import *
from ..models import AccessObject, Assignment, Level
from ..forms import AccessFormField
from django.forms import ModelForm, ValidationError
from django.forms.models import modelformset_factory, ModelForm
import datetime


class AssignmentModelForm(ModelForm):
    class Meta:
        model = Assignment
        exclude = ('access_object', )


AssignmentFormSet = modelformset_factory(Assignment, form=AssignmentModelForm)


class AccessFormFieldTestCase(ArmAccessTestCase):
    def setUp(self):
        super(AccessFormFieldTestCase, self).setUp()
        self.field = AccessFormField()

    def testCleanExistingAccessObject(self):
        obj = AccessObject.objects.create()
        self.assertEqual(self.field.clean(obj.id), obj.id)

    def testCleanEmptyFormSet(self):
        formset = AssignmentFormSet({
                'test-TOTAL_FORMS': 0,
                'test-INITIAL_FORMS': 0,
            }, prefix='test')
Пример #50
0
from django import forms
from .models import Book, BookImage
from django.forms.models import modelformset_factory


class BookCreatebyISBNForm(forms.Form):
    isbn = forms.CharField(max_length=14, help_text='10 or 13 Character')


class BookCreatebyISBNForm2(forms.ModelForm):
    class Meta:
        model = Book
        fields = ('price', 'category', 'city', 'condition')


class ImageForm(forms.ModelForm):
    image = forms.ImageField(label='Image')

    class Meta:
        model = BookImage
        fields = ('image', )


ImageFormSet = modelformset_factory(BookImage, form=ImageForm, extra=2)
Пример #51
0
            poll.question = poll_question
            poll.duration = poll_duration
            poll.max_options = poll_max_options
            poll.user_changes = poll_user_changes
            poll.save()

            for form in self.forms:
                form.instance.poll = poll
        super().save(commit)


TopicPollOptionFormset = modelformset_factory(
    TopicPollOption,
    TopicPollOptionForm,
    formset=BaseTopicPollOptionFormset,
    can_delete=True,
    extra=2,
    max_num=machina_settings.POLL_MAX_OPTIONS_PER_POLL,
    validate_max=True,
)


class TopicPollVoteForm(forms.Form):
    def __init__(self, poll, *args, **kwargs):
        self.poll = poll
        super().__init__(*args, **kwargs)

        if poll.max_options == 1:
            self.fields['options'] = forms.ModelChoiceField(
                label='',
                queryset=poll.options.all(),
Пример #52
0
class RequireFirst(BaseModelFormSet):
    def clean(self, *args, **kwargs):
        super(RequireFirst, self).clean()
        has_one = False
        for form in self.forms:
            if 'command' in form.cleaned_data and form.cleaned_data[
                    'DELETE'] == False:
                has_one = True
        if not has_one:
            raise ValidationError('At least one command must be specified')


TaskParameterFormset = modelformset_factory(TaskParameter,
                                            form=TaskParameterForm,
                                            can_order=True,
                                            can_delete=True,
                                            extra=1)
TaskCommandFormset = modelformset_factory(TaskCommand,
                                          form=TaskCommandForm,
                                          can_order=True,
                                          can_delete=True,
                                          extra=2,
                                          formset=RequireFirst)


def task_create_form(name, request, id, args={}):
    form_objects = {
        'task': TaskForm,
    }
    return create_form(form_objects, name, request, id, args)
Пример #53
0
def people_handler(request, blogger=None, format='html'):
    user = request.user

    # GET request with no specific user, so what is needed is a list of users.
    if request.method == 'GET' and blogger is None:
        bloggers = User.objects.filter(is_superuser__exact=False)
        data = {
            'bloggers':
            map(
                lambda b: {
                    'username': b.username,
                    'full_name': b.get_full_name()
                }, bloggers)
        }
        if format == 'html':
            return render_to_response('people/index.html',
                                      data,
                                      context_instance=RequestContext(request))
        elif format == 'json':
            return HttpResponse(json.dumps(data), mimetype='application/json')

    # GET request with a specific user, so show that user's blog.
    elif request.method == 'GET' and blogger is not None:
        data = {
            'blogger': {
                'username': blogger.username,
                'full_name': blogger.get_full_name()
            }
        }
        if format == 'html':
            if blogger.id == user.id:
                PosterboardFormSet = modelformset_factory(Posterboard)
                data['posterboard_formset'] = PosterboardFormSet()
            return render_to_response('people/show.html',
                                      data,
                                      context_instance=RequestContext(request))
        elif format == 'json':
            return HttpResponse(json.dumps(data), mimetype='application/json')

    # DELETE request, to delete that specific blog and user. Error for now.
    elif request.method == 'DELETE' and blogger is not None and \
            (blogger.id == user.id and blogger.username == user.username):
        # Trying to delete themselves? Not handling it for now.
        data = {
            'blogger': {
                'username': blogger.username,
                'full_name': blogger.get_full_name()
            },
            'errors': 'User deletion not supported this way.'
        }
        if format == 'html':
            return render_to_response('people/show.html',
                                      data,
                                      context_instance=RequestContext(request))
        elif format == 'json':
            return HttpResponse(json.dumps(data), mimetype='application/json')

    # All other types of requests are invalid for this specific scenario.
    error = {'errors': 'Invalid request'}
    if format == 'html':
        return render_to_response('people/index.html',
                                  error,
                                  context_instance=RequestContext(request))
    elif format == 'json':
        return HttpResponse(json.dumps(error),
                            mimetype='application/json',
                            status=400)
Пример #54
0
            for f in self.forms if not f.cleaned_data.get('DELETE', False)
        ])
        if not any(d['role'] == amo.AUTHOR_ROLE_OWNER for d in data):
            raise forms.ValidationError(_('Must have at least one owner.'))
        if not any(d['listed'] for d in data):
            raise forms.ValidationError(
                _('At least one team member must be listed.'))
        users = [d['user'] for d in data]
        if sorted(users) != sorted(set(users)):
            raise forms.ValidationError(
                _('A team member can only be listed once.'))


AuthorFormSet = modelformset_factory(AddonUser,
                                     formset=BaseAuthorFormSet,
                                     form=AuthorForm,
                                     can_delete=True,
                                     extra=0)


class DeleteForm(happyforms.Form):
    reason = forms.CharField(required=False)

    def __init__(self, request):
        super(DeleteForm, self).__init__(request.POST)


def ProfileForm(*args, **kw):
    # If the add-on takes contributions, then both fields are required.
    addon = kw['instance']
    fields_required = (kw.pop('required', False)
Пример #55
0
        }

    def save_with_user_and_add_to_count(self, user):
        """
        Method to save an Order, associate the order with a given user and add one to the count
        of the MenuItem choice.

        Arguments:

        **user**
            An User model object to associate the current entry to be saved with.
        """
        order = super().save(commit=False)
        order.user = user
        order.save()
        cur_choice = order.item_choice
        cur_choice.count = F('count') + 1
        cur_choice.save()
        return order

# ModelFormSet based on the MenuItem model, just asks for the name of the menu item,
# used for dynamic forms in the create and edit menu views.
MenuItemFormSet = modelformset_factory(
    MenuItem,
    fields=('item_text',),
    labels={'item_text': ("Nombre del plato")},
    can_delete=True,
    min_num=1,
    extra=0,
    validate_min=True)
Пример #56
0
        ])
        if not any(d['role'] == amo.AUTHOR_ROLE_OWNER for d in data):
            raise forms.ValidationError(
                ugettext('Must have at least one owner.'))
        if not any(d['listed'] for d in data):
            raise forms.ValidationError(
                ugettext('At least one author must be listed.'))
        users = [d['user'] for d in data]
        if sorted(users) != sorted(set(users)):
            raise forms.ValidationError(
                ugettext('An author can only be listed once.'))


AuthorFormSet = modelformset_factory(AddonUser,
                                     formset=BaseAuthorFormSet,
                                     form=AuthorForm,
                                     can_delete=True,
                                     extra=0)


class DeleteForm(happyforms.Form):
    slug = forms.CharField()
    reason = forms.CharField(required=False)

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

    def clean_slug(self):
        data = self.cleaned_data
        if not data['slug'] == self.addon.slug:
Пример #57
0
        super().__init__(*args, **kwargs)


class ConstraintForm(forms.ModelForm):
    start_time = TimeField(label=_('from (time)'), required=True)
    end_time = TimeField(label=_('to (time)'), required=True)
    weight = forms.ChoiceField(label=_('weighting'), choices=WEIGHT_CHOICES)

    class Meta:
        model = Constraint
        fields = ('start_time', 'end_time', 'weight')


UserConstraintFormSet = modelformset_factory(Constraint,
                                             formset=BaseConstraintFormSet,
                                             extra=0,
                                             exclude=('meeting', 'user'),
                                             can_delete=True,
                                             form=ConstraintForm)


class SubmissionReschedulingForm(forms.Form):
    from_meeting = forms.ModelChoiceField(Meeting.objects.none(),
                                          label=_('From meeting'),
                                          initial=0)
    to_meeting = forms.ModelChoiceField(Meeting.objects.none(),
                                        label=_('To meeting'),
                                        initial=0)

    def __init__(self, *args, **kwargs):
        submission = kwargs.pop('submission')
        super().__init__(*args, **kwargs)
Пример #58
0
from django.http import HttpResponse

from polls.models import Question
from django.template.context import RequestContext
from django.shortcuts import render_to_response, redirect
from polls.models import Author,Book
from django.forms.models import modelformset_factory
from django.forms import ModelForm
from django.shortcuts import get_object_or_404

class AuthorForm(ModelForm):
    class Meta:
        model = Author     

BookFormset = modelformset_factory( Book, 
    fields=('book_name', 'publisher_name'), extra=1, 
    can_delete=False) 


class UserSubmittedBookForm(ModelForm):
    class Meta:
        model = Book


def index1(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([p.question_text for p in latest_question_list])
    return HttpResponse(output)


def index(request):
Пример #59
0
    timestamp = models.DateTimeField(auto_now_add=True, null=True)
    #images = models.ManyToManyField("Image")
    entry = models.CharField(max_length=50)

    def __unicode__(self):
        return self.title


class AnnouncementForm(ModelForm):
    class Meta:
        model = Announcement
        exclude = ('entry', 'timestamp')


AnnouncementFormSet = modelformset_factory(Announcement,
                                           max_num=0,
                                           exclude=('entry', ))


class FinanceRequest(models.Model):
    user = models.ForeignKey(User)
    description = models.TextField(default="", blank=True)
    reimburse_name = models.CharField(max_length=40)
    student_id_or_group_num = models.CharField(max_length=40)
    address = models.TextField(default="", blank=True)
    is_approved = models.BooleanField(default=False)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    receipt_file = models.OneToOneField("File", null=True)
    timestamp = models.DateTimeField(auto_now_add=True, null=True)
    is_answered = models.BooleanField(
        default=False)  #whether or not an admin responded
Пример #60
0
def photos_batch_edit(request, photoset_id=0, template_name="photos/batch-edit.html"):
    """ change multiple photos with one "save button" click """
    photo_set = get_object_or_404(PhotoSet, id=photoset_id)
    if not photo_set.check_perm(request.user, 'photos.change_photoset'):
        raise Http403

    PhotoFormSet = modelformset_factory(
        Image,
        exclude=(
            'title_slug',
            'creator_username',
            'owner_username',
            'photoset',
            'is_public',
            'owner',
            'safetylevel',
            'exif_data',
            'allow_anonymous_view',
            'status',
            'status_detail',
        ),
        extra=0
    )

    if request.method == "POST":
        photo = Image.objects.get(pk=request.POST['id'])

        form = PhotoBatchEditForm(request.POST, instance=photo)

        if form.is_valid():

            if 'delete' in request.POST:
                photo.delete()

            photo = form.save()
            EventLog.objects.log(instance=photo)
            # set album cover if specified
            chosen_cover_id = request.POST.get('album_cover')

            if chosen_cover_id:
                # validate chosen cover
                valid_cover = True
                try:
                    chosen_cover = photo_set.image_set.get(id=chosen_cover_id)
                except Image.DoesNotExist:
                    valid_cover = False
                if valid_cover:
                    try:
                        cover = AlbumCover.objects.get(photoset=photo_set)
                    except AlbumCover.DoesNotExist:
                        cover = AlbumCover(photoset=photo_set)
                    cover.photo = chosen_cover
                    cover.save()

            return HttpResponse('Success')

        else:
            return HttpResponse('Failed')

    else:  # if request.method != POST

        # i would like to use the search index here; but it appears that
        # the formset class only accepts a queryset; not a searchqueryset or list
        photo_qs = Image.objects.filter(photoset=photo_set).order_by("position")
        photo_formset = PhotoFormSet(queryset=photo_qs)

    cc_licenses = License.objects.all()

    groups = Group.objects.filter(status=True, status_detail="active")

    if not request.user.profile.is_superuser:
        filters = get_query_filters(request.user, 'user_groups.view_group', **{'perms_field': False})
        groups = list(groups.filter(filters).distinct())

        users_groups = request.user.profile.get_groups()
        for g in users_groups:
            if g not in groups:
                groups.append(g)

    tag_help_text = Image._meta.get_field('tags').help_text

    default_group_id = Group.objects.get_initial_group_id()

    return render_to_resp(request=request, template_name=template_name, context={
        "photo_formset": photo_formset,
        "photo_set": photo_set,
        "cc_licenses": cc_licenses,
        "tag_help_text": tag_help_text,
        "groups": groups,
        'default_group_id': default_group_id
    })